Originally posted by Stephanie Grasson:
Judy,
The difference is as follows:
String = "abc";
creates a String [b]literal, which goes into the String pool.
String = new String("abc");
create a new String object.
If you have many String literals with the same value, they only get put in the String pool once. For example:
String s1 = "abc";
String s2 = "abc";
String s3 = "abc";
Only one String literal is created in the String pool. s1, s2 and s3 all refer to the same String literal. Hence,
s1 == s2 is true.
s2 == s3 is true.
s3 == s1 is true.
On the other hand,
String s1 = new String("abc");
String s2 = new String("abc");
String s3 = new String("abc");
Three unique String objects are created by the lines above. Hence,
s1 == s2 is false;
s2 == s3 is false;
s3 == s1 is false;
Hope this helps.
Stephanie
[This message has been edited by Stephanie Grasson (edited September 28, 2000).][/B]
Allen
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals method (�20.12.9), then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.
All literal strings and string-valued constant expressions are interned (�3.10.5).
Allen
Let's go back to the original question...the difference between
String s = "abc";
String s = new "abc";
...
Either statement will create a new String object provided that just one of the two statements are used. The issue of the string pool comes into play when a second reference is created to the same string, "abc." Is this not correct?
Allen
Starting in SDK 1.2, constant strings are shared between classes, reducing the memory needs of all classes. Since Java Strings are immutable, you don't need to worry about some other class changing your class's String.
It seems to me that using the statment
String s = "abc";
is somewhat more risky because the programmer may not know if "abc" is going to be in the String pool. Is this an accurate appraisal?
See ya later boys, I think I'm in love. Oh wait, she's just a tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
|