Thursday, 14 July 2022

Format a string using string formatted method

Java15 introduced ‘formatted’ method in String class to support formatting functionality on string objects or literal.

 

Signature

public String formatted(Object... args)

This method is equivalent to String.format(this, args), and return a formatted string.

 

Example

String str1 = "Hi my name is %s, and my age is %d";
String formattedStr1 = str1.formatted("Krishna", 32);

Can I call formatted method on text blocks?

Since text blocks are internally strings, we can call formatted method on them.

 

Example

String textBlock1 = """
Hi my name is %s and
my age is %d
""";

String formattedtextBlock1 = textBlock1.formatted("Krishna", 32);

Find the below working application.


 

 

FormattedMethodDemo.java

package com.sample.app;

public class FormattedMethodDemo {
	public static void main(String[] args) {
		String str1 = "Hi my name is %s, and my age is %d";
		String formattedStr1 = str1.formatted("Krishna", 32);

		System.out.println("formattedStr1 : " + formattedStr1);

		String textBlock1 = """
				Hi my name is %s and
				my age is %d
				""";
		String formattedtextBlock1 = textBlock1.formatted("Krishna", 32);

		System.out.println("\nformattedtextBlock1 : " + formattedtextBlock1);

	}

}

Output

formattedStr1 : Hi my name is Krishna, and my age is 32

formattedtextBlock1 : Hi my name is Krishna and
my age is 32

References

https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/lang/String.html#formatted(java.lang.Object...)


Previous                                                 Next                                                 Home

No comments:

Post a Comment