Java String intern Method

The Java intern method is one of the String Methods which is to return the canonical representation of the string object. This article shows how to write the Java String intern method with an example, and the syntax of it is

public String intern();

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

Java String intern Example

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

First, we declared two variables, str1 and str2, and assigned corresponding values using the first two Java statements.

Next, we declared two String objects, str3, and str4, and assigned non-Unicode text values.

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

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 function Example