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) {
       Scanner scanner = new Scanner(;
       String firstString;
       StringBuffer secondString;

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

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

           System.out.println("Both Strings are equal.");
           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.

Similar tutorials :

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊