How to Compare Strings in Java

QASource Engineering Team | October 7, 2024

How To Compare Strings in Java

In Java, comparing strings can be done using a variety of methods tailored to different needs. Below are the most commonly used methods for comparison:

  1. Using `==` operator

    This compares the objects' reference (memory address), not the content.

    ```java
    String str1 = "hello";
    String str2 = "hello";
    System.out.println(str1 == str2); // true, because both refer to the same object in the string pool
    
    String str3 = new String("hello");
    System.out.println(str1 == str3); // false, because str3 refers to a different object
    ```
  2. Using `equals()` method

    This compares the content of the strings.

    ```java
    String str1 = "hello";
    String str2 = new String("hello");
    System.out.println(str1.equals(str2)); // true, because their content is the same
    ```
  3. Using `equalsIgnoreCase()` method

    This compares the content of the strings, ignoring case differences.

    ```java
    String str1 = "hello";
    String str2 = "HELLO";
    System.out.println(str1.equalsIgnoreCase(str2)); // true, because their content is the same, ignoring case
    ```
  4. Using `compareTo()` method

    This method compares two strings lexicographically. It returns:

    • `0` if the strings are equal
    • A negative number if the first string is lexicographically less than the second string
    • A positive number if the first string is lexicographically greater than the second string
    ```java
    String str1 = "apple";
    String str2 = "banana";
    System.out.println(str1.compareTo(str2)); // negative number, because "apple" is less than "banana"
    ```
  5. Using `compareToIgnoreCase()` method

    This method compares two strings lexicographically, ignoring case differences.

    ```java
    String str1 = "apple";
    String str2 = "Banana";
    System.out.println(str1.compareToIgnoreCase(str2)); // negative number, because "apple" is less than "Banana" ignoring case
    ```

In Java, string comparison methods vary depending on whether you must compare memory references, content, or lexicographical order and whether case sensitivity matters. Choose the method that best suits your specific needs.

Disclaimer

This publication is for informational purposes only, and nothing contained in it should be considered legal advice. We expressly disclaim any warranty or responsibility for damages arising out of this information and encourage you to consult with legal counsel regarding your specific needs. We do not undertake any duty to update previously posted materials.

Post a Comment

Categories