Example & Tutorial understanding programming in easy ways.

How do you check if two Strings are equal in Java?

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


import java.util.Scanner;

class Comparetest{

public static void main(String args[]) {

String s1, s2;

Scanner test = new Scanner(System.in);   //  for command line

System.out.println("Enter the first string");

s1 = test.nextLine();

System.out.println("Enter the second string");

s2 = test.nextLine();

if ( s1.compareTo(s2) > 0 )

System.out.println("First string is greater than second.");

else if ( s1.compareTo(s2) < 0 )

System.out.println("First string is smaller than second.");


System.out.println("Both strings are equal."); }}

Read More →