6

I am not able to understand usage of intern method provider by String class.

String s1 = "vivek"; //Stmt 1
String s2 = "vivek"; //Stmt 2
String s3 = s1.intern(); //Stmt 3

System.out.println(s1 == s2);// prints true
System.out.println(s1 == s3);// prints true

I read that internally compiler do an intern, but on which object? How do compiler knows he had to do intern for s1 to create s2?

What is the difference between Stmt 2 and Stmt 3 here? Are both same always? If yes, what is so special about intern method of java?

Vivek Vardhan
  • 1,118
  • 3
  • 21
  • 44
  • @Mohammad I read that answer already, but I am confused by what is the difference between the two methods of String creation. Creation of `s2` and `s3` in above example?? – Vivek Vardhan Apr 07 '18 at 14:26
  • The Java compiler automatically interns all string literals. Therefore s1, s2 and s3 are all interned. They all point to the same thing. – DodgyCodeException Apr 07 '18 at 14:50

3 Answers3

3

The difference is that the initialization way of the variable that decides where to save the variable ;

  1. if it has the same value and same initialization method and initialized using new keyword - it will save it in heap and will save each variable as new object even if it has same value.
  2. if it has the same value and same initialization method and initialized directly - it will reference it in JVM pooled memory .

String Interning Oracle reference .

There are two ways to construct a string: implicit construction by assigning a string literal or explicitly creating a String object via the new operator and constructor. For example

String s1 = "Hello";              // String literal
String s2 = "Hello";              // String literal
String s3 = s1;                   // same reference
String s4 = new String("Hello");  // String object
String s5 = new String("Hello");  // String object

Java has provided a special mechanism for keeping the String literals - in a so-called string common pool. If two string literals have the same contents, they will share the same storage inside the common pool. This approach is adopted to conserve storage for frequently-used strings. On the other hand, String objects created via the new operator and constructor are kept in the heap. Each String object in the heap has its own storage just like any other object .

enter image description here

s1 == s1;         // true, same pointer
s1 == s2;         // true, s1 and s1 share storage in common pool
s1 == s3;         // true, s3 is assigned same pointer as s1
s1.equals(s3);    // true, same contents
s1 == s4;         // false, different pointers
s1.equals(s4);    // true, same contents
s4 == s5;         // false, different pointers in heap
s4.equals(s5);    // true, same contents

Important Notes:

  1. In the above example, I used relational equality operator '==' to compare the references of two String objects. This is done to demonstrate the differences between string literals sharing storage in the common pool and String objects created in the heap. It is a logical error to use (str1 == str2) in your program to compare the contents of two Strings.
  2. String can be created by directly assigning a String literal which is shared in a common pool. It is uncommon and not recommended to use the new operator to construct a String object in the heap.
Mohammad
  • 739
  • 7
  • 22
2

since when you create a string like : String s1="vivek"; this string is created in the string constant pool, and a reference is returned to "s1".

When you are using intern method to create a string like: s3=s1.intern(); This intern method returns the reference from the string constant pool only. Thats why both string are same as both contains reference to same string object.

refer the below image: enter image description here

But if u create a string like :

String s1=new String("vivek"); //---here one "vivek" will be stored in string constant pool and second "vivek" will be stored in heap area and "s1" contains reference to string in heap area 

String s2="vivek";  
String s3=s1.intern();//returns string from pool, now it will be same as s2  
System.out.println(s1==s2);//false because reference is different  
System.out.println(s2==s3);//true because reference is same  
akash verma
  • 159
  • 1
  • 15
  • String s1=new String("vivek"); -> does it create a constant in the pool as well? Becoz, in the following comment it says, with new operator, string will be created only in the heap and not pool – Arasn Aug 11 '19 at 16:53
2

What does intern() method do in Java?

String object created by new operator is by default not added in String pool as opposed to String literal. The intern method allows putting a String object into a pool. You can use intern() method to intern a String object and store them into String pool for further reuse. For example, when you create a String literal e.g. String s1="abc", it's automatically stored in String pool, but when you create a new String object e.g. String s1=new String("abc"), even though it's same String, a new object at a different memory location is created. This is a duplicate String. By calling the intern() method on this object, you can instruct JVM to put this String in the pool and whenever someone else creates "abc", this object will be returned instead of creating a new object. This way, you can save a lot of memory in Java, depending upon how many Strings are duplicated in your program. Example:

String s4 = new String("abc");
s4 = s4.intern();
String s5 = "abc";
System.out.println(s4==s5); // true

As you are trying to use intern method in the scenario where already strings are in string constant pool and refering to same reference so i think there is no use of intern method in your scenario. You will find more info here hope this will help you...

Prashant Patil
  • 371
  • 2
  • 13
  • `String object created by new operator is by default not added in String pool`? Are you sure? because I read that the "abc" after executing first statement, will be added to String pool. – Vivek Vardhan Apr 07 '18 at 15:10
  • 1
    @VivekVardhan yes i am sure . you read this in case of literal but in case of string object creation using new operater string is not added to string constant pool – Prashant Patil Apr 07 '18 at 15:14
  • @VivekVardhan i have edited my answer a little to avoid confusion plz see – Prashant Patil Apr 07 '18 at 15:15