
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print Formatted Text Using printf Method in Java
In Java, formatted text refers to those text that has been processed and arranged according to a specific format. According to the article, we will use the printf() method to learn how to print the formatted text.
Formatted Text using printf() Method
In Java, to print the formatted output or text we have a printf() method. 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.
Following is the syntax of the Java printf() method -
System.out.printf("format-string" [, arg1, arg2, ...]);
Here,
- format-string ? A format string that specifies how the text and values should be arranged. It can contain plain text, format specifiers (like %s, %d, %f, etc.), and escape sequences (like \n and \t).
- args ? Zero or more arguments that will be formatted and inserted into the format string (text).
Example 1
The following is a basic example of printing formatted text using the printf() method and the %s format specifier.
public class formattedText { public static void main(String[] args) { String str = "Tutorialspoint"; // Printing the original string System.out.println("The original string: " + str); // Printing the formatted string using printf() System.out.printf("Formatted text: %s", str); } }
Output
Following is the output of the above program:
The original string: Tutorialspoint Formatted text: Tutorialspoint
Example 2
The following is another example of printing formatted text using the printf() method. Here, we use format specifiers to align the string and integer values within a specified width:
public class formattedText { public static void main(String[] args) { String name = "Adithya"; int age = 30; System.out.printf("%10s - %4d%n", name, age); } }
Output
The above program prints the formatted string with a leading space of 10 characters for the name:
Adithya - 30