
- Java Tutorial
- Java - Home
- Java - Overview
- Java - Environment Setup
- Java - Basic Syntax
- Java - Object & Classes
- Java - Constructors
- Java - Basic Datatypes
- Java - Variable Types
- Java - Modifier Types
- Java - Basic Operators
- Java - Loop Control
- Java - Decision Making
- Java - Numbers
- Java - Characters
- Java - Strings
- Java - Arrays
- Java - Date & Time
- Java - Regular Expressions
- Java - Methods
- Java - Files and I/O
- Java - Exceptions
- Java - Inner classes
- Java Object Oriented
- Java - Inheritance
- Java - Overriding
- Java - Polymorphism
- Java - Abstraction
- Java - Encapsulation
- Java - Interfaces
- Java - Packages
- Java Advanced
- Java - Data Structures
- Java - Collections
- Java - Generics
- Java - Serialization
- Java - Networking
- Java - Sending Email
- Java - Multithreading
- Java - Applet Basics
- Java - Documentation
- Java Useful Resources
- Java - Questions and Answers
- Java - Quick Guide
- Java - Useful Resources
- Java - Discussion
- Java - Examples
How to print a formatted text using printf() method in Java?n
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
- Related Articles
- How to print % using printf()?
- How to format date using printf() method in Java?
- How to format time using printf() method in Java?
- Formatted text in Linux Terminal using Python
- Display localized month name with printf method in Java
- Write a program to print message without using println() method in java?
- Formatted Output in Java
- How to print colored text in the console using JavaScript?
- How to get formatted JSON in .NET using C#?
- How to use formatting with printf() correctly in Java?
- What is the correct way to use printf to print a size_t in C/C++?
- Date Formatting Using printf
- How to use the SimpleDateFormat class to convert a Java Date to a formatted String?
- How to print date using GregorianCalendar class in Java?
- Formatted Strings Using Template Strings in JavaScript

Advertisements