Printing the formatted text with printf in Java

By IncludeHelp Last updated : January 02, 2024

Printing the formatted text

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

The System.out.printf() Method

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.

Example

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

OR

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

Escape Sequences with System.out.printf()

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.

Example

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");

OR

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.

Example

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

Example

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 Main {
  public static void main(String[] args) {
    int a, b, sum;
    float average;

    a = 10;
    b = 20;

    sum = a + b;
    average = sum / 2;

    System.out.printf("Sum is= %d\n", sum);
    System.out.printf("Average is= %f\n", average);

  }
}

Output

Sum is= 30
Average is= 15.000000

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.