Sunday, July 12, 2009

printf() method in Java 5

The format() and printf() methods were added to java.io.PrintStream with java 5.

Syntax of printf() method in java 5:

printf("format string", argument (s));

The point to remember here is that, formatting data will always start with a percent sign (%).

For Example:
System.out.printf("%1$d + %2$d", 10, 20);

Output:
10 + 20

Here, as we can see, inside the double quotes, is a format string. 1$ represents the first argument. Similarly, 2$ represents the second argument. + sign is used to add a + symbol. d character is a conversion character.

Now, lets watch out for complete syntax:

% [arg_index$] [flags] [width] [.precision] conversion char


  1. arg_index An integer value followed by $. arg_index indicates which argument should be printed in this position.
  2. flags Following is the list of some of the flags:
    "-" Left justify the argument
    "+" Include a (+ or -) sign with the argument
    "0" Pad the argument with zeros
    "," Use comma in argument (like 100,678)
    "(" Enclose nagitive numbers in parentheses

  3. width Determines minimum of characters to be printed

  4. precision Used for formatting with floating point numbers. precision determines the number of digits to be printed after decimal point.

  5. conversion Type of argument to be formatted. For Example:
  • b boolean

  • c char

  • d integer

  • f floating point

  • s string

1 comment:

  1. Thanks

    This information is very useful for me, as i am fresher this will help me a lot.

    Good work.

    ReplyDelete