Home > Java > Java Tutorial > body text

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

WBOY
Release: 2023-09-21 18:57:03
forward
766 people have browsed it

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, … ]);
Copy after login

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);
   }
}
Copy after login

Output

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

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

Output

Adithya    -   30
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!