Java String.contentEquals() Method Example

1. Introduction

The String.contentEquals() method in Java is used to compare a String with a StringBuffer or another String to check if they have the same sequence of characters. This method returns a boolean value: true if the contents are equal, otherwise false. This tutorial will demonstrate the use of contentEquals() with examples.

Key Points

- The contentEquals() method is used to compare the exact content of a String with a StringBuffer or another String.

- It returns a boolean value.

- Useful for verifying if two text contents are exactly the same.

2. Program Steps

1. Declare a string and a StringBuffer.

2. Compare the string with the StringBuffer using the contentEquals() method.

3. Print the result of the comparison.

3. Code Program

public class StringContentEqualsExample {
    public static void main(String[] args) {
        // Declare the String
        String str1 = "Java Programming";
        // Declare the StringBuffer
        StringBuffer strBuffer = new StringBuffer("Java Programming");
        // Compare str1 with strBuffer
        boolean isEqual = str1.contentEquals(strBuffer);
        // Print the comparison result
        System.out.println("Is the content equal? " + isEqual);
    }
}

Output:

Is the content equal? true

Explanation:

1. String str1 = "Java Programming": Declares and initializes a String variable str1.

2. StringBuffer strBuffer = new StringBuffer("Java Programming"): Creates a StringBuffer strBuffer and initializes it with the same content as str1.

3. boolean isEqual = str1.contentEquals(strBuffer): Uses the contentEquals() method to compare str1 with strBuffer.

4. System.out.println("Is the content equal? " + isEqual): Prints the result of the comparison to the console.


Comments