Menu Close

Compare two strings lexicographically in Java

Write a java program to compare two strings lexicographically.

Lexicographical order is nothing but the dictionary order or preferably the order in which words appear in the dictionary.


If the strings are equal then mentions as follows:

Input:
ichigo                 // Ichigo means strawberry in japanese
ichigo

Output:
ichigo is equal to ichigo
import java.io.*;
import java.util.*;
public class temp{
  public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter String 1:  ");
    String s1=sc.nextLine();
    System.out.println("Enter String 2:  ");
    String s2=sc.nextLine();
    int res=s1.compareTo(s2);
    if (res>0)
    System.out.println(s1+ " is greater than " + s2);
    else if (res<0)
    System.out.println(s1+ " is less than " + s2);
    else
    System.out.println(s1+ " is equal to " + s2);
  }
}

INPUT_1:
Enter String 1:  fcukthecode.com

Enter String 2:  fuckthecode.com

OUTPUT:
fcukthecode.com is less than fuckthecode.com


INPUT_2:
Enter String 1:  Batman

Enter String 2:  Ball

OUTPUT:
Batman is greater than Ball


INPUT_3:
Enter String 1:  Monkey D. luffy

Enter String 2:  Gecko Moria

OUTPUT:
Monkey D. luffy is greater than Gecko Moria


INPUT_4:
Enter String 1:  Ichigo

Enter String 2:  Ichigo

OUTPUT:
Ichigo is equal to Ichigo


INPUT_5:
Enter String 1:  Program

Enter String 2:  Programming

OUTPUT:
Program is less than Programming


INPUT_6:
Enter String 1:  this

Enter String 2:  That

OUTPUT:
this is greater than That


INPUT_7:
Enter String 1:  This

Enter String 2:  That

OUTPUT:
This is greater than That


ILLUSTRATION

eXecuted using javac in linux terminal