Java: Strings – code examples
Text block and formatted
Strings#textblock#json#formatted
Use case: Embed multi-line JSON, SQL or HTML readably in code.
public class Main {
public static void main(String[] args) {
String name = "Ada";
String json = """
{
"name": "%s",
"alter": %d
}
""".formatted(name, 36);
System.out.print(json);
}
}The indentation is removed relative to the closing """, quotation marks need no escaping. formatted fills in the placeholders.
Formatted output
Strings#format#printf#stringbuilder
Use case: Print tables, reports and logs in fixed columns.
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String zeile = String.format(Locale.ROOT, "%-10s|%5d|%8.2f", "Ada", 36, 3.14159);
System.out.println(zeile);
var sb = new StringBuilder();
for (int i = 1; i <= 3; i++) sb.append(i).append(i < 3 ? ", " : "");
System.out.println(sb);
}
}%-10s = left-aligned, 10 characters, %5d = integer right-aligned, %8.2f = decimal number with 2 decimal places. Locale.ROOT enforces the decimal point. Output: Ada | 36| 3.14 and 1, 2, 3.
Counting words with merge
Strings#map#merge#text#treemap
Use case: Text analysis, e.g. most frequent words in a document.
import java.util.*;
public class Main {
public static void main(String[] args) {
String text = "this is a test this is fun";
Map<String, Integer> zaehler = new TreeMap<>();
for (String w : text.split(" ")) {
zaehler.merge(w, 1, Integer::sum);
}
System.out.println(zaehler);
}
}merge creates the value 1 or adds 1 to it. The TreeMap sorts alphabetically. Output: {a=1, fun=1, is=2, test=1, this=2}.