How to print a formatted text using printf() method in Java?


The printf() method allows us to format output to a java.io.PrintStream or java.io.PrintWriter. These classes also contain a method called format() which can produce the same results, so whatever we read here for the printf() method can also be applied to the format() method.

Syntax

System.out.printf(“format-string” [, arg1, arg2, … ]);

Example1

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);
   }
}

Output

Decimal: 1,234 Octal: 2322 Hex: 4d2
Tutorials Point


Example2

public class PrintfTest2 {
   public static void main(String[] args) {
      String name = "Adithya";
      int age= 30;
      System.out.format("%-10s - %4d\n", name, age);
   }
}

Output

Adithya    -   30
raja
Published on 08-Aug-2019 11:49:35
Advertisements