Skip Top Navigation Bar

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