Strings and StringBuilder

Introduction

Almost every program handles text: names, messages, file contents, commands. Java's String class comes with dozens of methods for searching, cutting and changing text. Two facts about strings explain most beginners' surprises: strings never change once made, and == does not compare their contents.

How it works

A String's characters are indexed from 0, like an array. length() counts them, charAt(i) returns one as a char, and substring(start, end) returns the part from start up to, but not including, end. indexOf("Java") finds where a piece first appears, or -1. contains, startsWith and endsWith answer yes-or-no questions, and toUpperCase, toLowerCase, trim and replace make changed copies.

Strings are immutable. No method changes a String; each returns a new one. Writing s.trim(); on its own line does nothing useful: you must keep the result, s = s.trim();.

To compare text, use equals: a.equals(b) compares the characters, and equalsIgnoreCase ignores case. The == operator compares whether two variables refer to the same object. Two equal strings made in different ways, such as one read from input and one written in the code, are different objects, so == says false. It sometimes appears to work, because Java reuses identical literals, which makes the bug hard to spot.

split(" ") cuts a string into an array of pieces, and String.join("-", parts) glues pieces together. String.format works like printf but returns the text.

A char is a number underneath, its Unicode code. 'a' + 1 is the int 98, and (char) ('a' + 1) is 'b'. Character.isLetter, Character.isDigit and Character.toUpperCase test and change single characters.

Because strings are immutable, s += x in a loop makes a new string each time, copying everything so far. For building text piece by piece, use a StringBuilder: append adds to the end, insert adds at a position, reverse reverses it, and toString gives the finished String.

Example

// Strings: methods, immutability, equals versus ==, StringBuilder and format.
public class Main {
    public static void main(String[] args) {
        String s = "  Hello, Java World  ";
        String t = s.trim(); // a new String: s itself never changes
        System.out.println("[" + t + "] " + t.length() + " " + t.toUpperCase());
        System.out.println(t.indexOf("Java") + " " + t.charAt(0) + " " + t.substring(7, 11) + " " + t.contains("World"));
        String[] words = t.split(" ");
        System.out.println(words.length + " " + words[1] + " " + String.join("-", words));
        String a = "java";
        String b = new String("java");
        System.out.println((a == b) + " " + a.equals(b) + " " + a.equalsIgnoreCase("JAVA"));
        StringBuilder sb = new StringBuilder();
        for (char c : "stressed".toCharArray()) sb.insert(0, c);
        System.out.println(sb + " " + String.format("%5.1f|%-4s|", 3.14159, "ok"));
    }
}
Open in compiler

Line by line

  1. trim returns a new string without the spaces at either end; s is unchanged.
  2. indexOf, charAt, substring and contains look inside t.
  3. split(" ") gives three words, and String.join glues them with dashes.
  4. a and b hold the same characters but are different objects: == is false, equals is true.
  5. Inserting each letter at the front reverses "stressed"; String.format pads 3.1 to 5 characters and "ok" to 4.

Expected result

[Hello, Java World] 17 HELLO, JAVA WORLD
7 H Java true
3 Java Hello,-Java-World
false true true
desserts   3.1|ok  |

In the real world

Web servers parse requests, apps validate e-mail addresses and passwords, and reports format numbers into tables, all with String methods. Comparing strings with == is a classic bug found in code reviews and by static analysis tools. Logging and report code builds large texts with StringBuilder, because repeated += can be many times slower.

Common mistakes

  • Comparing strings with == instead of equals.
  • Calling a method and ignoring its result, such as name.trim();.
  • Off-by-one substring ends: substring(0, 3) gives three characters, indexes 0 to 2.
  • Building long text with += in a loop, which copies the whole string each time.

Best practices

  • Compare with equals, putting a literal first ("yes".equals(answer)) so a null answer cannot crash.
  • Use StringBuilder in loops, and String.format or printf for layout.
  • Check indexOf results against -1 before using them as positions.

Summary

Strings are immutable sequences of characters indexed from 0, with methods to measure, search, cut, split and change copies of them. Compare them with equals, never ==. Characters are numbers underneath, and StringBuilder builds text efficiently when it is assembled piece by piece.

Quick check

1. How should two strings' contents be compared?
2. What does "Java".substring(1, 3) return?
3. After String s = " hi "; s.trim(); what is s?
4. Why use StringBuilder in a loop?

Key takeaways

  • Strings are immutable: trim, toUpperCase and replace return new strings.
  • Always compare strings with equals (or equalsIgnoreCase), never with ==.
  • Build text in loops with a StringBuilder, not with += on a String.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.