Java String intern
The java string intern() method returns the interned string. So in java we have various ways to create a String.
The java string intern() method returns the interned string. So in java we have various ways to create a String.
1. By String class constructor.
String str = new String ("Hello");
here two objects will get created in the memory one in side the heap on object area and another one inside the string constant pool but str will hold the reference of the string that is created under object area.
2. By literal.
Here only one object will get created inside the string constant pool.
3. By toString() Method on any object (String representation of an object). (same as first)
Now what if we want the string object from SCP(String constant pool), so to get the string reference from SCP java provides intern method.
Method Signature
The signature of intern method is given below:
public String intern()
Lets understand the things by example:
package net.jubiliation.example;
public class StringInterMethodExample {
public static void main(String[] args) {
String s1 = new String("hello"); (Two objects one on object area and another one at SCP)
String s2 = "hello"; // here s2 will hold the reference from SCP.
String s3 = s1.intern();// returns string from pool, now it will be same as s2
Method Signature
The signature of intern method is given below:
public String intern()
Lets understand the things by example:
package net.jubiliation.example;
public class StringInterMethodExample {
public static void main(String[] args) {
String s1 = new String("hello"); (Two objects one on object area and another one at SCP)
String s2 = "hello"; // here s2 will hold the reference from SCP.
String s3 = s1.intern();// returns string from pool, now it will be same as s2
System.out.println(s1 == s2);// false because s1 reference is from object area.
System.out.println(s2 == s3);// true because reference is same.
}
}
Comments
Post a Comment