Reusability of Strings in java?

Yes, to make things simpler you can think of it as picking from same address, but to be more precise variables are holding same reference which is number/objectID which JVM use while mapping to proper memory address of object (object can be moved in memory but will still have same reference).

You can test it with code like this:

String w1 = "word";
String w2 = "word";
String b = new String("word"); // explicitly created String (by `new` operator) 
                               // won't be placed in string pool automatically
System.out.println(w1 == w2);  // true  -> variables hold same reference
System.out.println(w1 == b);   // false -> variable hold different references,
                               // so they represent different objects
b = b.intern(); // checks if pool contains this string, if not puts this string in pool, 
                // then returns reference of string from pool and stores it in `b` variable
System.out.println(w1 == b);   // true  -> now b holds same reference as w1

In the case of

String h = "hi";
String i = "hi";
String j = new String("hi");

Depending on the version of the JDK the compiler may do what is called interning and create a single instance of the byte data that represents the "hi" and reuse it between the to variable references. In the most recent specifications all String literals are interned into the String pool in the Permanent Generation.

Using the new keyword as in the last statement will create a new instance of the exact same bytes as a separate object.

String objects created at runtime are not in the String pool unless .intern() is called on them. This is usually not needed and can cause problems, rarely has any significant benefits.

h == i; // true
h == j; // false
j.intern();
h == j; // true

Tags:

Java