Nil Nil - 5 months ago 13
Java Question

Reusability of Strings in java?

String h = "hi";

here we are referencing string h to string literal hi. JVM has a string literal pool to store string literals so we can reuse the strings as they re immutable...

When we say
what is the exact meaning of this? are we talking about the
? that it is picked from same address evey time ?


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 - identifier which JVM can use to map to proper memory address of object (since objects can be moved in memory).

You can test it by code like this:

String w1 = "word";
String w2 = "word";
String b = new String("word"); // explicitly creating String by calling `new` operator 
                               // won't put it in string pool
System.out.println(w1 == w2);  // true  -> variables hold same reference
System.out.println(w1 == b);   // false -> variable hold different references
b = b.intern(); // check if pool contains this string, if not put this string in pool, 
                // then return reference of such string from pool and store it in b variable
System.out.println(w1 == b);   // true  -> now w1 and b hold same reference