tags:

views:

128

answers:

2

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

This code on ideone

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 to valueOf(double), but the intern() method is right after ;) )
Colin Hebert
You mean to say that only intern() will check whether the string exist in pool.
sadananda salam
@sadananda salam, yes.
Colin Hebert
@colin: String hello = "Hello"; System.out.print((hello == ("Hel"+"lo"))); //i dint use intern but it returns true.
sadananda salam
@sadananda salam, here the compiler saw that it could be simplified as "Hello" directly, so "Hel"+"lo" == "Hello" at compile time.
Colin Hebert
+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
@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
@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