Write a Java Program to Compare Two Strings using compareTo() Function

By | 09.02.2017

Java Program to 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.

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

 

SOURCE CODE ::

 

import java.util.Scanner;
 
class Compare_Strings
{
   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.");
   }
}

 

OUTPUT ::

 

run:

Enter the first string
CodezClub
Enter the second string
CodezWorld
First string is smaller than second.

BUILD SUCCESSFUL (total time: 8 seconds)

 

4.5 4 votes
Article Rating
Category: Java Programming String Programs Tags:

About Tunde A

My name is Tunde Ajetomobi, a Tech Enthusiast and Growth Hacker. I enjoy creating helpful content that solves problem across different topics. Codezclub is my way of helping young aspiring programmers and students to hone their skills and find solutions on fundamental programming languages.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments