Java String Comparison: '==' vs '.equals()' vs '.compareTo()'

This tutorial explores the intricacies of comparing strings in Java. We'll break down the differences between using the '==' operator, the '.equals()' method, and the '.compareTo()' method for string comparison.

Understanding the Core Concepts

  • String Literals and the String Pool: Java maintains a special area in memory called the 'string pool'. When you create a string using literals (e.g., 'String str = 'Hello';'), the JVM checks if an identical string already exists in the pool. If it does, the variable 'str' references that existing string. If not, a new string is created in the pool.

  • String Objects: You can also create strings using the 'new' keyword (e.g., 'String str = new String('Hello');'). This always creates a new string object in the heap, even if an identical string exists in the string pool.

Comparison Methods Explained

  1. '==' Operator: This operator checks for reference equality. It returns 'true' only if the two variables being compared point to the same memory location (i.e., the same object).

    
    System.out.println(cString == dString); // Output: false   ```
    
    In this example, 'cString' and 'dString' contain the same sequence of characters but refer to different objects. Hence, '==' returns 'false'.
    
    
  2. '.equals()' Method: This method compares the actual content of the strings. It returns 'true' if both strings have the same characters in the same order, case-sensitive.

    java System.out.println(cString.equals(dString)); // Output: true

    Here, '.equals()' correctly identifies that 'cString' and 'dString' have the same content, despite being different objects.

  3. '.compareTo()' Method: This method provides a lexicographical comparison. It returns:

    • 0: if both strings are lexicographically equal. * Negative value: if the calling string is lexicographically less than the argument string. * Positive value: if the calling string is lexicographically greater than the argument string.

    java System.out.println(cString.compareTo(dString)); // Output: 0

    In this case, 'compareTo' returns 0, indicating the strings are lexicographically equal.

Key Takeaways

  • Use '==' for comparing object references and '.equals()' for comparing string content.* The '.compareTo()' method is valuable for sorting strings lexicographically.* Be mindful of the string pool when comparing strings created with literals.

By mastering these concepts, you can write more robust and efficient Java code when dealing with string comparisons.

Java String Comparison: A Deep Dive with Examples

原文地址: https://www.cveoy.top/t/topic/RKY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录