Write a program to get the canonical representation of the string object


This Java program demonstrates the use of the intern method and compares two strings using the == operator.

  • The program defines a public class named "Canonical" with a main method that takes no arguments. The main method declares three String variables str1, str2, and str3.
  • The first String variable str1 has the value "Java Exercises".
  • The second String variable str2 is created using a StringBuffer object that concatenates the strings "Java" and " Exercises", and then converts the result to a String.
  • The third String variable str3 is obtained by invoking the intern method on str2. This method returns a canonical representation for the string object, which means it returns the same reference for all equal string objects.
  • The program then compares str1 and str2 using the == operator and prints the result. This comparison checks if the two String variables refer to the same object in memory.
  • The program also compares str1 and str3 using the == operator and prints the result. Since str3 is obtained by interning str2, it should return true if str1 and str2 have the same characters.

Source Code

public class Canonical
{
	public static void main(String[] args)
	{
		String str1 = "Java Exercises";
		String str2 = new StringBuffer("Java").append(" Exercises").toString();
		String str3 = str2.intern();
 
		System.out.println("str1 == str2 ? " + (str1 == str2));
		System.out.println("str1 == str3 ? " + (str1 == str3));
	}
}

Output

str1 == str2 ? false
str1 == str3 ? true

Example Programs