Strings, Text and Formatting in Java
Strings are immutable
Every modification creates a new object. Repeated concatenation in a loop is therefore slow.
String s = "PrepVerse";
String t = s.toUpperCase(); // new String; s is unchanged
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) {
sb.append(i).append(','); // one mutable buffer
}
String csv = sb.toString(); // "0,1,2,3,4,"
The string pool
Literals are interned in a pool, so equal literals can share one object. This is why == sometimes works, and why you must still use equals.
String a = "java";
String b = "java";
String c = new String("java");
System.out.println(a == b); // true (same pooled object)
System.out.println(a == c); // false (different object)
System.out.println(a.equals(c)); // true (same characters)
Useful methods
| Method | Example result |
|---|---|
length(), charAt(i) | length and a character |
substring(1, 4) | part of a string |
indexOf("x"), contains("x") | search |
split(",") | array of parts |
trim(), strip(), isBlank() | whitespace handling |
replace("a", "b"), repeat(3) | transform |
String.join(",", list) | combine |
Formatting
String line = String.format("%-10s %5d %8.2f", "Asha", 21, 91.5);
System.out.println(line); // "Asha 21 91.50"
String json = """
{
"name": "PrepVerse",
"tracks": 9
}
"""; // text block (Java 15+)
Regular expressions
import java.util.regex.*;
Pattern p = Pattern.compile("(\\w+)@(\\w+\\.com)");
Matcher m = p.matcher("write to asha@prepverse.com today");
if (m.find()) {
System.out.println(m.group(1)); // asha
System.out.println(m.group(2)); // prepverse.com
}
Optional instead of null
import java.util.Optional;
Optional<String> name = findName(42);
String shown = name.map(String::toUpperCase).orElse("UNKNOWN");
Return Optional from methods that may have no result; do not use it for fields or method parameters.
Loading Comments...