Java program to compare two strings using contentEquals method

Java program to compare two strings using contentEquals() method :

In this Java tutorial, we will learn how to use contentEquals() method to compare two strings. The syntax of contentEquals() method is as below :

public boolean contentEquals(StringBuffer s)

Means, we need to pass one StringBuffer variable to this method to compare. It will return true if both string and the stringbuffer are equal, else it will return false. Let’s take a look at the below example :

Java example program :

import java.util.*;

public class Main {

    public static void main(String[] args) {
        //1
       Scanner scanner = new Scanner(System.in);
       String firstString;
       StringBuffer secondString;

       //2
       System.out.println("Enter the first string : ");
       firstString = scanner.nextLine();

       //3
       System.out.println("Enter the second string : ");
       secondString = new StringBuffer(scanner.nextLine());

       //4
       if(firstString.contentEquals(secondString)){
           System.out.println("Both Strings are equal.");
       }else{
           System.out.println("Strings are not equal.");
       }

    }

}

Explanation :

The commented numbers in the above example denote the step number below :

1. Create one new Scanner object to read user input string. Create one String variable firstString to store the first string and create another variable secondString to store the second string. This variable is a StringBuffer variable.
2. Ask the user to enter a string .Read it and store it in firstString variable.
3. Ask the user to enter the second string. Read it using scanner and convert it to a StringBuffer variable and store it in secondString variable.
4. Compare both strings using contentEquals method. Pass the StringBuffer variable to this method and check if the return value is true or false. Print out the message accordingly.

Sample Output :

Enter the first string : 
hello world
Enter the second string : 
hello world
Both Strings are equal.

Enter the first string : 
hello world
Enter the second string : 
hello earth
Strings are not equal.

Leave a Reply