w3resource

Java: Get the canonical representation of the string object


20. Get Canonical Representation

Write a Java program to get the Canonical representation of the string object.

Sample Solution:

Java Code:

// Define a public class named Exercise20.
public class Exercise20 {
    // Define the main method.
    public static void main(String[] args) {
        // Create three strings in three different ways.
        String str1 = "Java Exercises"; // Creating a string using string literal
        String str2 = new StringBuffer("Java").append(" Exercises").toString(); // Creating a string using StringBuffer and converting it to string
        String str3 = str2.intern(); // Creating a string by interning str2

        // Determine which strings are equivalent using the ==
        // operator (as compared to calling equals(), which is
        // a more expensive operation.
        System.out.println("str1 == str2? " + (str1 == str2)); // Checking if str1 and str2 reference the same object
        System.out.println("str1 == str3? " + (str1 == str3)); // Checking if str1 and str3 reference the same object
    }
}

Sample Output:

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

Flowchart:

Flowchart: Java String  Exercises -  Get the canonical representation of the string object


For more Practice: Solve these Related Problems:

  • Write a Java program to compare the canonical representations of two strings after normalization.
  • Write a Java program to convert a string to its canonical form and check equality with another string.
  • Write a Java program to demonstrate canonical representation by comparing interned and non-interned strings.
  • Write a Java program to generate canonical representations of strings and sort them lexicographically.

Go to:


PREV : Get Index of Alphabet Characters.
NEXT : Last Index of Character.

Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.