Text is everywhere — input, output, files, JSON — and String has a few rules that trip up every newcomer.
A String is an object holding a sequence of characters, and it is immutable: methods like toUpperCase() or replace() return a new string and leave the original unchanged. If you ignore the return value, nothing happens.
Compare string contents with a.equals(b) (or equalsIgnoreCase), never with ==. == checks whether two references point at the same object; it sometimes appears to work because string literals are shared, then fails for strings built at runtime.
Useful methods: length(), charAt(i), substring(start, end) (end is exclusive), indexOf, contains, startsWith, strip() (trims whitespace), isBlank(), split(","), repeat(n), and String.join(", ", list).
Concatenation with + is fine for a few pieces. In a loop, use a StringBuilder, which is mutable and avoids creating a new string each iteration: sb.append(x) then sb.toString().
For formatting, String.format("%s is %d years", name, age) or the instance form "%.2f".formatted(price) work like printf.
Since Java 15, text blocks make multi-line strings readable. They start with """ followed by a newline; the common indentation is stripped automatically:
String json = """
{"name": "Ana", "age": 31}
""";Inside text blocks you don't need to escape double quotes, which makes them great for JSON, SQL and HTML snippets.
Example
public class Strings {
public static void main(String[] args) {
String name = " Ada Lovelace ";
String clean = name.strip(); // "Ada Lovelace"
name.toUpperCase(); // result ignored: name unchanged
String typed = new String("Ada Lovelace"); // a different object
System.out.println(clean == typed); // false
System.out.println(clean.equals(typed)); // true
System.out.println(clean.substring(0, 3)); // Ada
System.out.println(String.join("|", clean.split(" "))); // Ada|Lovelace
var sb = new StringBuilder();
for (int i = 1; i <= 3; i++) sb.append(i).append(',');
System.out.println(sb); // 1,2,3,
String html = """
<p>Hello, %s</p>
""".formatted(clean);
System.out.print(html); // <p>Hello, Ada Lovelace</p>
}
}Remember
- Strings are immutable — always use the returned value
- Compare contents with
equals, never== - Use
StringBuilderin loops and text blocks for multi-line text
Watch out for
- Writing
s.trim();on its own line and expectingsto change. - Comparing user input with
==— it fails for strings created at runtime.