Build and transform text with String methods, format output, and do calculations with operators and the Math class.
Why: the + operator glues strings together. When you join many pieces (especially in a loop) a StringBuilder is faster because it does not create a new string each time.
String first = "Ada";
String last = "Lovelace";
String full = first + " " + last; // "Ada Lovelace"
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(", ");
sb.append("world");
System.out.println(sb.toString()); // "Hello, world"Why: Strings come with methods for the things you do constantly — change case, trim spaces, search, and slice. Strings are immutable, so each method returns a new string instead of changing the original.
String text = " Hello, World ";
System.out.println(text.trim()); // "Hello, World"
System.out.println(text.toUpperCase()); // " HELLO, WORLD "
System.out.println(text.contains("World")); // true
System.out.println(text.trim().substring(0, 5)); // "Hello"
System.out.println(text.trim().replace("World", "Java")); // "Hello, Java"Why: this trips up every beginner — use .equals() to compare string contents, NOT ==. The == operator checks whether two variables point at the exact same object, which is usually not what you want for text.
String a = "hello";
String b = "hel" + "lo";
System.out.println(a.equals(b)); // true — same content
System.out.println(a.equalsIgnoreCase("HELLO")); // true
// System.out.println(a == b); // unreliable — never compare text this wayWhy: building strings with lots of + gets messy. formatted() (or String.format) inserts values into placeholders: %s for a string, %d for a whole number, %.2f for a decimal with 2 places.
String name = "Ada";
int score = 95;
double price = 19.5;
String line = "%s scored %d (%.2f credits)".formatted(name, score, price);
System.out.println(line); // "Ada scored 95 (19.50 credits)"Why: when you need text spanning several lines — JSON, SQL, HTML — a text block keeps it readable. Open and close with triple quotes; the line breaks and indentation are preserved.
String json = """
{
"name": "Ada",
"active": true
}
""";
System.out.println(json);Why: the basic operators (+ - * /) cover arithmetic, and the Math class provides the rest — powers, roots, rounding, and min/max. Math methods are static, so you call them on Math directly.
System.out.println(Math.pow(2, 10)); // 1024.0 (2 to the power 10)
System.out.println(Math.sqrt(144)); // 12.0
System.out.println(Math.max(3, 9)); // 9
System.out.println(Math.round(3.7)); // 4
System.out.println(Math.abs(-5)); // 5
System.out.println(Math.random()); // a random double from 0.0 to 1.0