I ran the following program,
String firstString = "String";
String secondString = "String";
String thirdString = new String("String");
System.out.println(firstString == secondString);
System.out.println(firstString == thirdString);
System.out.println(firstString.intern() == thirdString);
System.out.println(firstString.intern() == thirdString.intern());
System.out.println(firstString.intern().equals(thirdString.intern()));
System.out.println(firstString == thirdString);
and my output was
true
false
false
true
true
false
I learnt that the jvm pools string with same content as same strings. Is that right? If thats true then why not the firstString == thirdString return false? Does jvm only pool the string only initialized with :"" and not with new operator?
Most of such questions can be solved using pointer based approach. One/more pointer approach. When you need to find the smallest/largest/ conditional substring from the given string, sliding window approach is the way to go. An example of such question would be: find the longest substring without repeating character.
The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is created.
The pooling relates to string literals only - so firstString
and secondString
are actually the same object - where as in thirdString
you explicitly asked for a new object to be created on the heap.
I recommend reading the section about string literals in the spec.
It provides more information on how and when strings are pooled.
Also, take note to these bullets at the end of the section:
- Literal strings within the same class (§8) in the same package (§7) represent references to the same String object (§4.3.1).
- Literal strings within different classes in the same package represent references to the same String object.
- Literal strings within different classes in different packages likewise represent references to the same String object.
- Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.
- Strings computed by concatenation at run time are newly created and therefore distinct.
For firstString and secondString, JVM will lookup the string pool and return the reference of "String".
For thirdString, JVM will not lookup the string pool and will only create a String object in heap.
For OneString.intern(), JVM will lookup the reference in string pool, add OneString to string pool if OneString does not exist in it, and return the reference.
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