liveBook · Manning

String

As explained in 100 Java Mistakes and How to Avoid Them

A string is a programming-language value representing an ordered sequence of characters or character units as text.

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

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains string comparison through interning, compile-time constants, runtime-created objects, consequences, prevention, and analysis tooling.
Examples
Uses literal and concatenated strings to contrast shared constant objects with separately created runtime objects.
What you can do after
Diagnose/debug with IntelliJ IDEA inspections or SonarLint, and replace == with equals() for string content comparisons.
How it connects
Connects strings with equals(), reference equality, compile-time constants, interning, object identity, and static analysis.

Also explained in

Compare how 24 books explain string →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.