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 ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With