Strings look simple but invite mistakes involving character representation, locales, formatting, regular expressions, escape sequences, indexing, and object comparison. One especially dangerous assumption is treating string equality as reference identity. section 6.0 section 7.1
Reference equality can appear to work
String greeting = "Hello"; System.out.println(greeting == "Hello"); // true String greeting2 = greeting + "!"; System.out.println(greeting2 == "Hello!"); // false Compile-time string constants may be interned, so the first comparison can share an object. The runtime-created greeting2 is a separate object. Use greeting2.equals("Hello!") for content comparison. section 7.1
Avoid string-comparison failures with these rules:
- Use equals() rather than == when comparing string contents; reserve reference equality for rare, profiled cases. section 7.1
- Treat a comparison that happens to succeed for literals as unreliable evidence that == is correct. section 7.1
- Use IntelliJ IDEA's String Comparison Using == inspection or SonarLint rule S4973 to detect string comparisons with ==. section 7.1























