GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing javaevolved.dev — String.formatted() | java.evolved
Strings
Beginner
String.formatted()Call formatted() on the template string itself. Code Comparison
✕ Java 8
String msg = String.format(
"Hello %s, you are %d",
name, age
);
✓ Java 15+
String msg =
"Hello %s, you are %d"
.formatted(name, age);
See a problem with this code? Let us know.
Why the modern way wins
📖
Reads naturallyTemplate.formatted(args) flows better than String.format(template, args). 🔗
ChainableCan be chained with other string methods. 📏
Less verboseDrops the redundant String.format() static call. Old Approach
String.format()
Modern Approach
formatted()
Since JDK
15
Difficulty
Beginner
JDK Support
String.formatted()
Available
Widely available since JDK 15 (Sept 2020) How it works
String.formatted() is an instance method equivalent to String.format() but called on the format string. It reads more naturally in a left-to-right flow. Related Documentation
Proof
Related patterns
Strings
Beginner
String.lines() for line splittingJava 8
String text = "one\ntwo\nthree";
String[] lines = text.split("\n");
for (String line : lines) {
System.out.println(line);
}
Java 11+
String text = "one\ntwo\nthree"; text.lines().forEach(IO::println);
JDK 11+
→
Strings
Beginner
String.strip() vs trim()Java 8
// trim() only removes ASCII whitespace // (chars <= U+0020) String clean = str.trim(); Java 11+
// strip() removes all Unicode whitespace String clean = str.strip(); String left = str.stripLeading(); String right = str.stripTrailing();
JDK 11+
→
Strings
Beginner
String.indent() and transform()Java 8
String[] lines = text.split("\n");
StringBuilder sb = new StringBuilder();
for (String line : lines) {
sb.append(" ").append(line)
.append("\n");
}
String indented = sb.toString();
Java 12+
String indented = text.indent(4);
String result = text
.transform(String::strip)
.transform(s -> s.replace(" ", "-"));
JDK 12+
→
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |