w3resource

Java: Get the canonical representation of the string object

Java String: Exercise-20 with Solution

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

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to get the index of all the characters of the alphabet.
Next: Write a Java program to get the last index of a string within a string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/java-exercises/string/java-string-exercise-20.php