Skip Top Navigation Bar

Create and assign simple strings of characters - Example 3

Snippet: Create and assign simple strings of characters using new String()

Explanation

This snippet introduces the new String() constructor as an alternative way to create a String. The variable message2 is created using new String(message1), which produces a new string with the same characters as message1.

Then, message1 is reassigned using new String("World"). When both variables are printed, message2 still holds "Hello" — just like with a plain assignment, reassigning message1 has no effect on message2. The new String() constructor creates an independent copy of the string's characters.

What You Can Do

Try comparing the two ways of creating a string: String s1 = "Hello" and String s2 = new String("Hello"). Do they print the same value?

They might behave differently when compared with == versus .equals() — can you find out why?

You can also try passing a string literal directly to the constructor, like new String("World"), versus passing a variable. Does it make a difference in the output?

Run it and observe the output!

Example List

Additional Resources