Home >Java >javaTutorial >How to print formatted text using printf() method in Java?

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

WBOY
WBOYforward
2023-09-21 18:57:03935browse

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

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.

Syntax

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

Example 1

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

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

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete