Skip to content
AgileLogics
4 min read

Strings

Prerequisites: Operators

String is an object with useful built-in methods, and — unlike arrays — is immutable: every method that looks like it modifies a string actually returns a brand new one.

String name = "Ada Lovelace";
System.out.println(name.length());          // 12
System.out.println(name.toUpperCase());      // ADA LOVELACE
System.out.println(name.substring(0, 3));    // Ada
System.out.println(name.contains("Love"));   // true
System.out.println(name.replace("Ada", "Grace")); // Grace Lovelace

Concatenate with +, or build longer strings efficiently with StringBuilder:

String greeting = "Hello, " + name + "!";

StringBuilder sb = new StringBuilder();
sb.append("Hello, ").append(name).append("!");
System.out.println(sb.toString());

Common mistakes

  • Concatenating strings with + inside a large loop — each + creates a new String object, which is wasteful; use StringBuilder for building a string incrementally instead.
  • Calling .equals() on a variable that might be null — this throws a NullPointerException. Put the literal first instead: "expected".equals(value).