Home » Java programming language

Java Console printf() Method with Example

Console Class printf() method: Here, we are going to learn about the printf() method of Console Class with its syntax and example.
Submitted by Preeti Jain, on March 31, 2020

Console Class printf() method

  • printf() method is available in java.io package.
  • printf() method is used to print a formatted string to this Console with the help of the given format string and parameters.
  • printf() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • printf() method may throw an exception at the time of formatting this Console.
    IllegalFormatException: This exception may throw when the given string format is not valid.

Syntax:

    public Console printf(String frmt , Object... params);

Parameter(s):

  • String frmt – represents the format string as defined in the Format string.
  • Object... params – represents the parameters addressed by the format specifiers in the format string.

Return value:

The return type of the method is Console, it returns this Console.

Example:

// Java program to demonstrate the example 
// of Console printf(String frmt , Object… params)
// method of Console

import java.io.*;

public class PrintFOfConsole {
 public static void main(String[] args) {
  try {
   // Instantiates Console 
   Console con = System.console();

   // Define a string format 
   String frmt = "%1$5s %2$20s %3$30s%n";

   // By using printf() method isto print the
   // the formatted given string 
   con.format(frmt, "S_Name", "S_Add", "S_ph");
   con.format(frmt, "Preeti", "Delhi", "9425667852");
   con.format(frmt, "Rahul", "Delhi", "8871459682");
   con.format(frmt, "Shreya", "Delhi", "7216589745");
   con.format(frmt, "Rama", "Bangalore", "8871568492");
   con.format(frmt, "Anjali", "London", "8872589261");

  } catch (Exception ex) {
   System.out.println(ex.toString());
  }
 }
}

Output

S_Name                S_Add                           S_ph
Preeti                Delhi                     9425667852
Rahul                Delhi                     8871459682
Shreya                Delhi                     7216589745
 Rama            Bangalore                     8871568492
Anjali               London                     8872589261


Comments and Discussions!

Load comments ↻





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