Skip to main content

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~!

Try it: comparing strings​

Quiz

Comparing strings

1 / 2

String a = "cat"; String b = "cat"; a == b vs a.equals(b) β€”

Pick an answer to see if you are right.


πŸ‘€ TODO: Trvia

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


Chapter summary​

Key takeaways
  1. Use .equals() (or .equalsIgnoreCase()) to compare the contents of two Strings β€” never ==, which compares object identity.
  2. .compareTo() returns negative, zero, or positive to say whether the calling string sorts before, equal to, or after the argument alphabetically.
  3. .equalsIgnoreCase() treats "Test" and "test" as equal; .equals() treats them as different.
  4. String comparison, like number comparison, gives you a boolean you can feed straight into if.

Exercises​

Activity: Alphabetical order

Read two words. Print them in alphabetical order, space-separated, using .compareTo().