String objects are immutable. What that means is that you cannot change the contents of a String object. You can have to variables referencing the same String object, but since the String object itself cannot be changed, you can't get strange effects.
Because String objects are immutable, the
Java compiler can safely implement an optimization trick. If you write a program in which you use the same literal string more than once, for example like this:
Then the Java compiler is smart enough to create only one String object with the content "Hello", and make the variables 'one' and 'two' refer to that single String object. This is good, because it saves memory.
If you do this:
Then you are explicitly creating two String objects with the same content "Hello". This is less memory-efficient.
There's no use ever to using new String("...") in a Java program, so
you should never write code that does that.
[ November 21, 2008: Message edited by: Jesper Young ]