Chapter 4d - String Comparison
using Equals() to compare Stringsโ
String hello1 = "Hello";
String hello2 = "Hello";
System.out.print(hello1.equals(hello2));
๐งช Try the code out~!
String word1 = "test"
String word2 = "Test"
System.out.print(word1.equals(word2));
System.out.println(word1.equalsIgnoreCase(word2));
๐งช 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~!
Dictionary Exerciseโ
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.in);
System.out.print("\n Enter the first word : ");
String word1=scan.nextLine();
System.out.print("\n Enter the second word : ");
String word2=scan.nextLine();
if(true){
System.out.println(word1 + " and " + word2 + " are lexicographically same");
}else if(true){
System.out.println(word1 + " ," + word2);
}else{
System.out.println(word2 + ", " + word1);
}
}
}
๐โโ๏ธ Sample Program