In java String can be created by using new operator or by using + and +=. So, does all these string creation techniques check whether the string already exist in the string pool. If they dint then which String creation technique will check the pool.
+3
A:
No they don't.
Simple example :
String s = new String("hell");
String hello = "hello";
s += 'o';
System.out.println(hello == hello.intern()); //True
System.out.println(s == s.intern()); //False
System.out.println(s == hello); //False
System.out.println(s.intern() == hello); //True
//To sum up : s != s.intern() == hello.intern() == hello
Here the new version of "s" isn't the internal version of "hello"
If you want to have the pool version of a specific string, you can use the intern()
method (just as I did above). This way you're sure to have the same reference.
Resources :
- Javadoc :
String.intern()
(you might think that the link points tovalueOf(double)
, but theintern()
method is right after ;) )
Colin Hebert
2010-10-03 15:03:07
You mean to say that only intern() will check whether the string exist in pool.
sadananda salam
2010-10-03 15:25:59
@sadananda salam, yes.
Colin Hebert
2010-10-03 15:27:37
@colin: String hello = "Hello"; System.out.print((hello == ("Hel"+"lo"))); //i dint use intern but it returns true.
sadananda salam
2010-10-03 15:31:52
@sadananda salam, here the compiler saw that it could be simplified as "Hello" directly, so "Hel"+"lo" == "Hello" at compile time.
Colin Hebert
2010-10-03 15:44:04
+2
A:
Only string constants and literals are automatically interned. If you're concatenating or otherwise creating strings, you need to actually call the intern() method. See http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#intern().
Kirk Woll
2010-10-03 15:04:54
@Kirk: you said concatenating and creating strings. is it string object concatenation or string constant/literal concatenation or both. String creation can be done by new, +, += operator. do i need to use intern for all the 3 operators.
sadananda salam
2010-10-03 15:38:17
@sadananda, my intent was actually just to cite examples. The **only** case where intern() is implicit is in the two cases (really just one, since they're the same) I mentioned of "string constants" and "string literals". All other forms of obtaining strings (+, +=, StringBuilder.toString(), etc.) will be new instances and not interned.
Kirk Woll
2010-10-03 15:41:51