Home » Java programming language

Printing the formatted text with printf in Java

We can use printf to print the formatted text in Java, this function is similar to C programming language's printf.

printf in Java is the method of System.out class, it is System.out.printf method, here 'f' stands for formatted.

Consider the given statement, here we are printing "Hello word" using System.out.printf() method.

System.out.printf("Hello world");


System.out.printf("%s","Hello world");

Here is the list of some common "Escape Sequences" that can be used with the System.out.printf method

\n - It stands for new line, it will set the position of cursor at the beginning of the next line.
\t - It stands for tab, it will move the cursor position to the next cursor stop
\r - It stands for carriage return, it will set the position of cursor at the beginning of the current line
\\ - It will print the single backslash character
\" - It will print the double quotes

Consider the given statement, it will print the "Hello     world" (Message in double quotes) and a line after the message.

System.out.printf("\"Hello \t world\"\n");


System.out.printf("%s\n","\"Hello \t world\"");

In the statement System.out.printf("%s\n","\"Hello \t world\""); first argument "%s\n" is the formatted string, that contains %s - to print the string and \n - to set the cursor at the beginning of the next line. The second argument is "\"Hello \t world\"" is the string to be printed.

Printing Character, Integer and Float values

Just like C language, System.out.printf method is able to print the character, integer, float and other type of values using format specifiers.

Here are the some common format specifiers

%d - Integer value
%f - Float value
%c - Character value
%s - String value

Consider the statement - this statement will print the values using format specifiers

System.out.printf("%c, %d, %f\n", 'X', 362436, 10.234f);

The output would be

X, 362436, 10.234000

Here is a program - Here we will get the sum and average of two integer number, to print the messages and values, we will use only System.out.printf method:

public class SumAndAvg{
     public static void main(String []args){
        int a,b,sum;
        float average;
        a=10; b=20; 
        System.out.printf("Sum is= %d\n",sum);
        System.out.printf("Average is= %f\n",average);


Sum is= 30
Average is= 15.000000


Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.