Java String intern Method

The Java String intern method is one of the String Methods, which is to return the canonical representation of the string object. In this article, we will show how to write the String intern method with an example. The syntax of the intern in the Java Programming language is

public String intern(); // It will return String as output 

//In order to use in program
String_Object.intern();

Java String intern Example

Here, We are going to use the String.intern method to return the canonical value of the user-specified string.

// Java String.intern method example
package StringFunctions;

public class InternMethod {
	public static void main(String[] args) {
		String str1 = "We are abc working in abc company";
		String str2 = "tutorialgateway.org";
		String str3 = new String("A" + "\u00ea" + "\u00f1" + "\u00fc" + "C");
		String str4   = new String("\u0048" + "\u0065" + "\u006C" + "\u006C" + "\u1D18");
		
		System.out.println("Canonical representation = " + str1.intern());
		System.out.println("Canonical representation = " + str2.intern());
		System.out.println("Canonical representation = " + str3.intern());
		System.out.println("Canonical representation = " + str4.intern());
	}
}
Java String intern Method 1

First, we declared two String variables str1, str2, and assigned corresponding values using the following Java statement.

String str1 = "We are abc working in abc company";
String str2 = "tutorialgateway.org";

Next, we declared two String objects str3, str4, and assigned a non-Unicode text values using the following statement.

String str3 = new String("A" + "\u00ea" + "\u00f1" + "\u00fc" + "C");
String str4   = new String("\u0048" + "\u0065" + "\u006C" + "\u006C" + "\u1D18");

The following System.out.println statements call public String intern () String Function to return the canonical representation of the above-specified string (str1, str2, str3 & str4)

System.out.println("Canonical representation = " + str1.intern());
System.out.println("Canonical representation = " + str2.intern());
System.out.println("Canonical representation = " + str3.intern());
System.out.println("Canonical representation = " + str4.intern());