Create and assign simple strings of characters - Example 2
Snippet: Create and assign simple strings of characters
Explanation
This snippet explores what happens when you assign one String variable to another. The variable message2 is assigned the value of message1, which at that point holds "Hello". Both variables now refer to the same string value.
Then, message1 is reassigned to "World". When both are printed, message2 still holds "Hello" — it was not affected by the change. This is because reassigning message1 only changes what message1 points to, not the value that message2 holds.
What You Can Do
Try reassigning message2 after the reassignment of message1. What do you expect to see?
You can also try adding a third variable message3 = message2 before the reassignment of message1. Does message3 change when message1 is reassigned? What about when message2 is reassigned?
Run it and observe the output!
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