codescracker


java

Java Program to Compare Two Strings



« Previous Program Next Program »


Compare Two Strings

To compare two string in Java Programming, you have to ask to the user to enter the two string and start comparing using the compareTo() method.

Java Programming Code to Compare Two Strings

Following Java Program ask to the user to enter the two string to check whether the two strings are equal or not :

/* Java Program Example - Compare Two String */
		
import java.util.Scanner;

public class JavaProgram
{
   public static void main(String args[])
   {
      String str1, str2;
      Scanner in = new Scanner(System.in);
 
      System.out.println("Enter First String");
      str1 = in.nextLine();
 
      System.out.println("Enter Second String");
      str2 = in.nextLine();
 
      if(str1.compareTo(str2) > 0)
      {
         System.out.println("First String is Greater than Second String.");
      }
      else if(str1.compareTo(str2) < 0)
      {
         System.out.println("First String is Smaller than Second String.");
      }
      else
      {
         System.out.println("Both Strings are Equal (i.e. String1 is Equal to String2)");
      }
   }
}

When the above Java Program is compile and executed, it will produce the following result. Above Java Programming Example Output (for equal strings):

Java Program compare two strings

Above Java Programming Example Output (for unequal strings):

compare two strings in java

Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test