Java program to compare two strings

Created with Sketch.

 

Java program to compare two strings

How to compare two strings in Java, i.e., test whether they are equal or not? The compareTo method of String class is used to test the equality of its two objects. The method is case sensitive, i.e., “java” and “Java” are two different strings for it. If you wish to compare them without considering their case use compareToIgnoreCase method.

String comparison in Java

import java.util.Scanner;

class CompareStrings
{
public static void main(String args[])
{
String s1, s2;
Scanner in = new Scanner(System.in);

System.out.println(“Enter the first string”);
s1 = in.nextLine();

System.out.println(“Enter the second string”);
s2 = in.nextLine();

if (s1.compareTo(s2) > 0)
System.out.println(“The first string is greater than the second.”);
else if (s1.compareTo(s2) < 0)
System.out.println(“The first string is smaller than the second.”);
else
System.out.println(“Both the strings are equal.”);
}
}

Output of program:
Java program to compare two strings output

 

String “hello” is greater than “Hello” because the ASCII value of ‘h’ is greater than that of ‘H.’ To check two strings for equality, you can use equals method that returns true if they are equal.

Leave a Reply

Your email address will not be published. Required fields are marked *