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 newStringobject, which is wasteful; useStringBuilderfor building a string incrementally instead. - Calling
.equals()on a variable that might benull— this throws aNullPointerException. Put the literal first instead:"expected".equals(value).