printf() method allows us to format the output to java.io.PrintStream or java.io.PrintWriter. These classes also contain a method called format() which produces the same result, so whatever we read here about the printf() method works Can be applied to the format() method.
System.out.printf(“format-string” [, arg1, arg2, … ]);
import java.io.PrintStream; public class PrintfTest1 { public static void main(String[] args) { int i = 1234; System.out.printf("Decimal: %1$,d Octal: %1$o Hex: %1$x"\n, i); String str = "Tutorials Point"; System.out.printf("%15s", str); } }
Decimal: 1,234 Octal: 2322 Hex: 4d2 Tutorials Point
##Example 2
public class PrintfTest2 { public static void main(String[] args) { String name = "Adithya"; int age= 30; System.out.format("%-10s - %4d\n", name, age); } }
Adithya - 30
The above is the detailed content of How to print formatted text using printf() method in Java?. For more information, please follow other related articles on the PHP Chinese website!