Strings

String is immutable, and == on it is almost always a mistake.

String is an object. The literal "Ann" lives in the string pool, while new String("Ann") creates another object with the same text. The == operator compares references, not letters. Two literals with the same text often point to the same object, so == passes by accident in a textbook example and fails on a string from the database or a request.

Compare with the equals method. When null is possible, Objects.equals(a, b) is safer: it never calls a method on null. Case matters. equalsIgnoreCase is a separate method, and you should not mix it in silently.

A string is immutable. text.toUpperCase() does not change text; it returns a new string. If you do not keep the result, the original string stays as it was. Long text built in a loop goes through StringBuilder, otherwise each + copies the growing piece.

length() counts UTF-16 code units, not "letters on the screen" for every character. For ordinary English or Russian text it matches the number of characters. For some emoji it does not. In a service that trims a nickname by length, remember this before a user sees a cut-off character.

Practice

  1. How to compare text

    Two strings were built in different ways, but the letters are the same. How do you check that the text is equal?

    • With the == operator
    • With the equals method
    • With the = operator
    • With the length method
  2. What toUpperCase returns

    There is String s = "ab". What does s equal after calling s.toUpperCase() if the result was not stored anywhere? Write the text of s.

  3. Reverse a string

    Write static String reverse(String s) that returns the characters of s in reverse order.