Skip to main content

Chapter 4d - String Comparison

using Equals() to compare Stringsโ€‹

String  hello1 = "Hello";
String hello2 = "Hello";
๐Ÿงช Try the code out~!
String  word1 = "test"
String word2 = "Test"
๐Ÿงช Try the code out~!

Using compareTo() to compare Strings:โ€‹

String s1 = "hello";
String s2 = "hello";
String s3 = "apple";
String s4 = "nation";
System.out.println(s1.compareTo(s2)); //0 because both are equal
System.out.println(s1.compareTo(s3)); //7 because "h" is 7 times greater than "a"
System.out.println(s1.compareTo(s4)); //-6 because "h" is 6 times lower than "n"
๐Ÿงช Try the code out~!

๐Ÿ‘€ TODO: Trvia

Dictionary Exerciseโ€‹


  • Modify this program so that it compares and orders two words lexicographically.
import java.util.Scanner;

class Main{
public static void main (String args[]){
Scanner scan=new Scanner(;
System.out.print("\n Enter the first word : ");
String word1=scan.nextLine();
System.out.print("\n Enter the second word : ");
String word2=scan.nextLine();

System.out.println(word1 + " and " + word2 + " are lexicographically same");
}else if(true){
System.out.println(word1 + " ," + word2);
System.out.println(word2 + ", " + word1);

๐Ÿ™‹โ€โ™€๏ธ Sample Program