Write a Java program to compare two strings
import java.util.Scanner;
class Compare1
{
public static void main(String args[])
{
String str1, str2;
Scanner in = new Scanner(System.in);
System.out.println("Enter the first string");
str1 = in.nextLine();
System.out.println("Enter the second string");
str2 = in.nextLine();
if (str1.compareTo(str2) > 0)
System.out.println("The first string is greater than the second.");
else if (str1.compareTo(str2) < 0)
System.out.println("The first string is smaller than the second.");
else
System.out.println("Both the strings are equal.");
}
}
Output:-
debug:
Enter the first string
India
Enter the second string
India
Both the strings are equal.
BUILD SUCCESSFUL (total time: 14 seconds)
import java.util.Scanner;
class Compare1
{
public static void main(String args[])
{
String str1, str2;
Scanner in = new Scanner(System.in);
System.out.println("Enter the first string");
str1 = in.nextLine();
System.out.println("Enter the second string");
str2 = in.nextLine();
if (str1.compareTo(str2) > 0)
System.out.println("The first string is greater than the second.");
else if (str1.compareTo(str2) < 0)
System.out.println("The first string is smaller than the second.");
else
System.out.println("Both the strings are equal.");
}
}
Output:-
debug:
Enter the first string
India
Enter the second string
India
Both the strings are equal.
BUILD SUCCESSFUL (total time: 14 seconds)