Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusability of Strings in java?

Tags:

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 reusable, what is the exact meaning of this? are we talking about the address ? that it is picked from same address evey time ?

like image 273
nr5 Avatar asked May 25 '12 18:05

nr5


1 Answers

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
like image 131
Pshemo Avatar answered Oct 02 '22 00:10

Pshemo