4 - String Comparisons

Get an introduction to or review of string comparison methods in Java programming.

Code HuntJava
1.0x

4 - String Comparisons

Created 3 years ago

Duration 0:06:28
lesson view count 41
Get an introduction to or review of string comparison methods in Java programming.
Select the file type you wish to download
Slide Content
Tags: Code Hunt Java
  1. Comparing Strings

    Slide 2 - Comparing Strings

  2. The equals() method

    Slide 3 - The equals() method

    • Strings cannot be compared with the == and != operators. Instead use the equals() method in the String class:
    • <string1>.equals(<string2>)
    • "cake".equals("cake")
    • "cake".equals("pie")
  3. Case-insensitive comparison

    Slide 4 - Case-insensitive comparison

    • The equals() method will only return true if the Strings are exactly the same:
    • "abc".equals("ABC")
    • "abc".equals("aBc")
    • To consider upper- and lower-case letters the same, use equalsIgnoreCase():
    • "abc".equalsIgnoreCase("ABC")
    • "abc".equalsIgnoreCase("aBc")
  4. String ordering

    Slide 5 - String ordering

    • Instead of using the < and > operators for Strings, we use the compareTo() method:
    • <string1>.compareTo(<string2>)
    • This method returns values as follows:
    • A negative number if string1 precedes string2
    • A positive number if string1 follows string2
    • Zero if string1 and string2 are equal
    • compareToIgnoreCase() treats upper- and lower-case letters as equal
  5. String ordering

    Slide 6 - String ordering

    • Since Strings can contain characters other than letters, ordering cannot simply be alphabetical.
    • Instead, we use lexicographic ordering, which works as follows:
    • Letters are ordered alphabetically
    • All uppercase letters precede all lowercase letters
    • Digits are in numerical order, and precede all letters
    • Spaces and most punctuation precede digits
    • Shorter Strings precede longer Strings
    • See the full character ordering at http://unicode-table.com/en/
  6. String ordering

    Slide 7 - String ordering

    • Examples:
    • "apple".compareTo("apple")
    • "apple".compareTo("banana")
    • "apple".compareTo("Apple")
    • "apple".compareTo("applE")
    • "apple".compareTo("Banana")
    • "apple".compareToIgnoreCase("Apple")
    • "apple".compareTo("apples")
    • "123".compareTo("234")
  7. Check Your Understanding

    Slide 8 - Check Your Understanding

  8. Check Your Understanding

    Slide 9 - Check Your Understanding

  9. Check Your Understanding

    Slide 10 - Check Your Understanding

  10. Check Your Understanding

    Slide 11 - Check Your Understanding