Home >>Java String Methods >Java String intern() method

Java String intern() method

Java String intern() method

The Intern() method in java string is used to returns the interned string. It returns the canonical string representation.

If it is generated with new keyword, it can be used to return string from memory. It creates exact copy of an object heap string in constant pool string.

Syntax

public String intern()

Java String intern() Method Example 1


public class InternExample1
{  
public static void main(String args[])
{  
String n1=new String("phptpoint");  
String n2="phptpoint";  
String n3=n1.intern(); 
System.out.println(n1==n2);
System.out.println(n2==n3);
}
}  

Output:
False
True

Java String intern() Method Example 2


public class InternExample2 
{
	public static void main(String[] args) 
	{		
		String v1 = "Phptpoint";
		String v2 = v1.intern();
		String v3 = new String("Phptpoint");
		String v4 = v3.intern();		
		System.out.println(v1==v2); 
                System.out.println(v2==v4);
		System.out.println(v1==v3); 
                System.out.println(v2==v3); 
		System.out.println(v1==v4); 			
		System.out.println(v3==v4); 		
	}
}

Output:
true
true
false
false
true
false

No Sidebar ads