Skip Top Navigation Bar

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