Saturday, April 4, 2015

Java program to compare two strings

Java program to compare two strings

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.

Java programming code

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("First string is greater than second.");
      else if ( s1.compareTo(s2) < 0 )
         System.out.println("First string is smaller than second.");
      else   
         System.out.println("Both strings are equal.");
   }
}
Download Compare strings program class file.
Output of program:
compare strings
String 'hello' is greater than 'Hello' as ASCII value of 'h' is greater than 'H'. To check two strings for equality you can use equals method which returns true if strings are equal otherwise false.

No comments:

Post a Comment

TestNG - Can i use the 2 different data providers to same @test methods in TestNG?

public Object [][] dp1 () { return new Object [][] { new Object [] { "a" , "b" }, new Obje...