In this example, we will write an example to help format a given string in Java through format () method.
Source Code
package com.beginner.examples;
public class StringFormatter {
public static void main(String[] args) {
//%s stands for string
String str = "I like %s";
//Print the formatted string
System.out.println(String.format(str, "java"));
//%d stands for integer
String str1 = "20 + 2 = %d";
System.out.println(String.format(str1, 22));
//%f stands for float
String str2 = "2.1 + 0.1 = %f";
System.out.println(String.format(str2, 2.2));
}
}
Output:
I like java
20 + 2 = 22
2.1 + 0.1 = 2.200000