7

With Java version 1.6 the output is false true, but with version 1.8 the output changed to true true.

Can some one explain why is this happening?

Intern method is used to refer the corresponding string constant pool of created objects in the heap, and if the object is not there then it will create a String constant pool. Please correct me if my understanding is wrong.

public class Intern_String2 {

 public static void main(String[] args) {

  String s1 = new String("durga");  //object created in heap

  String s2 = s1.concat("software");
  //object durga software created in heap at runtime

  String s3 = s2.intern();
  // create durga software object in string constant pool as none exist.

  System.out.println(s2==s3);//should be false but print true in 1.8 version.

  String s4 = "durgasoftware";
  System.out.println(s3==s4);//prints true in both version..      
 }
}
Christian
  • 25,249
  • 40
  • 134
  • 225
kumar Anny
  • 346
  • 4
  • 12

3 Answers3

2

String.intern() returns the canonical instance of String. But it does allow that the String you passed to intern() (e.g. the call receiver / object you call the method on) is returned -- this may happen if String is not in the internal table yet -- that is the canonical instance now. In the same way, if that String was already in the internal String table, intern() would return it.

String s2 = "web".concat("sarvar");
String s3 = s2.intern();
System.out.println(s2 == s3); // prints "true"

String s4 = "web".concat("sarvar");
String s5 = s4.intern();
System.out.println(s4 == s5); // prints "false"
Aleksey Shipilev
  • 18,599
  • 2
  • 67
  • 86
1

I would say that this happens at JAVA6 because the String pool was implemented used the PermGen... later, at JAVA7, the String.intern() begins to use the HEAP memory...

See this link for more details...

Carlitos Way
  • 3,279
  • 20
  • 30
  • 2
    Nothing you describe here would change the output of the program in the question. – user2357112 Jul 20 '16 at 20:24
  • 1
    @user2357112: Java 8: the first string came in the string pool, and the intern gave back this same string pool entry. So Carlitos is correct, intern no longer is that special, superfluous actually. – Joop Eggen Jul 20 '16 at 20:39
0

The jls does specify what becomes part of the constant pool. String literals and stuff retrieved by String.intern().

There are no real specification when it becomes part of it(First use, or load of the class defining the literal). It also doesnt state what doesnt become part of it, and what other stuff might be interned.

So based on your experiment i guess they changed the part when Strings become part of the constant pool. Basically changed it from loading of the class to first use. So String.intern() can return "this" while still adding this to the constant pool becoming the same instance with the literal as as it is first used.

k5_
  • 5,450
  • 2
  • 19
  • 27