Intern method concept confusion as output changed with different version

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) {
  // TODO Auto-generated method stub

  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..

 }

String.intern() returns the canonical instance of String. But it does allow that the String you passed to intern() (eg 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"

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...


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.

链接地址: http://www.djcxy.com/p/35464.html

上一篇: 确定未定义函数的参数类型

下一篇: 作为输出的实习生方法概念混淆随着不同版本而改变