Originally posted by Jesper Young: A string literal is text enclosed in double quotes in your source code. A String object is an object of type String.
Ok i too visualize same(as stated by u).But then
String s = new String("abcdef");.......(A) // creates a string object. String s = "abcdef";....................(B) //string literal.
why is it said that both (A) and (B) create a new String object, with a value of �abcdef �, and assign it to a reference variable s.
Joined: Oct 13, 2005
Strings are peculiar in Java. They are immutable, and they have another strange bit of behaviour.
You have actually created two String objects in that bit of code. A String literal is a String object too.
This has a String whose value is "abcdef". This is a String object, and because you have written out its value in full, it is called a String literal. Then, you use the new operator to create a new object, which is another String. It happens to have the same value. So at this point your memory contains two String objects
The next bit of code uses a String literal with the value abcdef. You have declared the same variable twice, so that bit won't compile. Let's change it to readNow, the compiler or the JVM goes through the code and sees abcdef. It thinks to itself, "I have seen that before," and lo and behold, there is "abcdef" in memory. So it uses that abcdef again. So what it does is to add a reference s2 to "abcdef". Now you have this situation:Two String objects, both with the value abcdef.
Try this little class. When you get == it shows that the two references point to the same object.That will show you which references are "equal" to each other, and which are duplicate references to the same object. You don't need s1 == s2 AND s2 == s1 because they give exactly the same result.
Added s4 as a field[/edit] [ December 21, 2007: Message edited by: Campbell Ritchie ]