Java Formatter class and Java printf() method

Introduction

We can use the printf() method with the format power from Java Formatter class.

The printf() method uses Formatter to create a formatted string.

It then displays that string on System.out, which is the console by default.

The printf() method is defined by both PrintStream and PrintWriter.

public class Main {
  public static void main(String args[]) {
    System.out.printf("Various integer formats: ");
    System.out.printf("%d %(d %+d %05d\n", 3, -3, 3, 3);

    System.out.println();/*from   w  w w.ja v  a 2  s  . c  om*/
    System.out.printf("Default floating-point format: %f\n", 1234567.123);
    System.out.printf("Floating-point with commas: %,f\n", 1234567.123);

    System.out.printf("Negative floating-point default: %,f\n", -1234567.123);
    System.out.printf("Negative floating-point option: %,(f\n", -1234567.123);

    System.out.println();

    System.out.printf("Line up positive and negative values:\n");
    System.out.printf("% ,.2f\n% ,.2f\n", 1234567.123, -1234567.123);
  }
}



PreviousNext

Related