String Comparison Example Java Program

Definition

A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements to be mutated and the length changed, or it may be fixed (after creation). A string is generally understood as a data type and is often implemented as an array of bytes (or words) that stores a sequence of elements. A string may also denote more general arrays or other sequence (or list) data types and structures.

Syntax

Variable_name1 = Variable_name2.compareTo(Variable_name3)

String Comparison Example Program

import java.util.Scanner;
 
class StringComparison{
	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");
		}
		else if ( str1.compareTo(str2) < 0 ){
			System.out.println("First string is smaller");
		}
		else{
			System.out.println("The strings are equal");// Strings are compared based on the length of the strings.
		}
	}
}

Sample Output

Output is:
Enter first string
hello
Enter second string
hai
First string is greater