You are here

Java program to compare two strings

Java program to compare two strings, i.e., test whether they are equal or not, compareTo method of String class is used to test equality of two String class objects. This method is case sensitive, i.e., "java" and "Java" are two different strings. If you wish to compare strings without considering case of the strings, then use compareToIgnoreCase method.

Java programming code

  1. import java.util.Scanner;
  3. class CompareStrings
  4. {
  5.    public static void main(String args[])
  6.    {
  7.       String s1, s2;
  8.       Scanner in = new Scanner(;
  10.       System.out.println("Enter the first string");
  11.       s1 = in.nextLine();
  13.       System.out.println("Enter the second string");
  14.       s2 = in.nextLine();
  16.       if (s1.compareTo(s2) > 0)
  17.          System.out.println("The first string is greater than the second.");
  18.       else if (s1.compareTo(s2) < 0)
  19.          System.out.println("The first string is smaller than the second.");
  20.       else  
  21.          System.out.println("Both the strings are equal.");
  22.    }
  23. }

Output of program:
Java program to compare two strings output

Download Compare strings program class file.

String 'hello' is greater than 'Hello' as ASCII value of 'h' is greater than that of 'H'. To check two strings for equality you can use equals method which returns true if the strings are equal.