Input/Output: printf

 

Java’s print() and println() methods are the ones that you have been using. The printf() method gives us more control over the appearance of the output.

  • Formatted printing basics. In its simplest form, printf() takes two arguments. The first argument is called the format string. It contains a conversion specification that describes how the second argument is to be converted to a string for output.

Format strings begin with % and end with a one-letter conversion code. The following table summarizes the most frequently used codes:

  • Format string. The format string can contain characters in addition to those for the conversion specification. The conversion specification is replaced by the argument value (converted to a string as specified) and all remaining characters are passed through to the output.
  • Multiple arguments. The printf() function can take more than two arguments. In this case, the format string will have an additional conversion specification for each additional argument.

Here is more documentation on printf format string syntax

[spoiler title=’TestPrintf’]

public class TestPrintf
{
   public static void main(String [] args)
   {
       System.out.println("123456789012345678901234567890");
       System.out.printf("%10.2f%8.2f",3.33333, 1234.5677865);
       System.out.println();
       for (int i = 0; i < 12; i++){
        System.out.printf("%2d%6d",i, i*i);
        System.out.println();
    }
        
    }
}

/**
123456789012345678901234567890
      3.33 1234.57
 0     0
 1     1
 2     4
 3     9
 4    16
 5    25
 6    36
 7    49
 8    64
 9    81
10   100
11   121

 */

[/spoiler]