19 Aralık 2022 Pazartesi

String.formatted metodu - Java 15 İle Geliyor

Giriş
Açıklaması şöyle. String.format() yerine direkt String şablonunu kullanıyoruz.
Since Java 15, you can now format a String with a new method, formatted. This method is the same as the well know static String format method. From a readability perspective, this is the same as String.format.

This newly added method will also be easier to test as the static alternative. Technically, you can now mock it with mockito. In practice, of course, you won’t be doing that very often. But it gives you some more possibilities, which is always lovely.
İmzası şöyle
public String formatted(Object... args)
Örnek
Şöyle yaparız
String msg = "Your name is %s and Your age is %d".formatted("Nick", 18);
System.out.println(msg); // Your name is Nick and Your age is 18
Örnek
Şöyle yaparız. Burada String.format ve String.formatted farkı görülebilir
var format = "Hello %s, how are you?\nIt's %d°C today!";
var greeting = String.format(format, name, tempC);

// Java 15+
var greeting = format.formatter(name, tempC);


Hiç yorum yok:

Yorum Gönder