forked from javaevolved/javaevolved.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring-formatted.yaml
More file actions
45 lines (45 loc) · 1.36 KB
/
string-formatted.yaml
File metadata and controls
45 lines (45 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
---
id: 33
slug: "string-formatted"
title: "String.formatted()"
category: "strings"
difficulty: "beginner"
jdkVersion: "15"
oldLabel: "Java 8"
modernLabel: "Java 15+"
oldApproach: "String.format()"
modernApproach: "formatted()"
oldCode: |-
String msg = String.format(
"Hello %s, you are %d",
name, age
);
modernCode: |-
String msg =
"Hello %s, you are %d"
.formatted(name, age);
summary: "Call formatted() on the template string itself."
explanation: "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."
whyModernWins:
- icon: "📖"
title: "Reads naturally"
desc: "Template.formatted(args) flows better than String.format(template, args)."
- icon: "🔗"
title: "Chainable"
desc: "Can be chained with other string methods."
- icon: "📏"
title: "Less verbose"
desc: "Drops the redundant String.format() static call."
support:
state: "available"
description: "Widely available since JDK 15 (Sept 2020)"
prev: "strings/string-indent-transform"
next: "strings/string-chars-stream"
related:
- "strings/string-lines"
- "strings/string-strip"
- "strings/string-indent-transform"
docs:
- title: "String.formatted()"
href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html#formatted(java.lang.Object...)"