Create and assign simple strings of characters - Example 1
Snippet: Create and assign simple strings of characters
Explanation
This snippet introduces how to create and assign a String variable in Java. Two variables, message1 and message2, are both initially assigned the value "Hello".
Then, message1 is reassigned to "World". When both variables are printed again, you can see that message2 still holds "Hello" — it was not affected by the change to message1. This shows that each variable holds its own reference to a string value.
What You Can Do
Try reassigning message2 as well — what do you expect to see when you print both variables?
Then try assigning message1 back to "Hello" after setting it to "World". What does the output look like then?
You can also try creating a third variable message3 and assigning it the value of message1 before the reassignment. Does message3 change when message1 is reassigned?
Run it and find out!
Example List
Additional Resources
- Learn: Declaring Strings
- Learn: Constructing a String
- Learn: Introduction to String Indexing
- Learn: Comparing Two String Objects Using compareTo Methods
- Learn: Comparing String Objects with equals Methods
- Learn: Obtaining Substrings from a String Object
- Learn: Using the split method on a String
- Practice: Evaluating Expressions that use the String Class
- Practice: Writing Code Using the String Class
- FRQ Practice: AP Computer Science A FRQ 1 Formatting Words
- FRQ Practice: AP Computer Science A FRQ 1 Sentence Analysis