From Wiki
Jump to navigationJump to search


  • String formatting can be done using the printf() and the format() methods added in (System.out is a PrintStream)
  • Internally they ise the java.util.Formatter class.
  • Basic format:

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

  • It can be cleaner to use:
  • When we want to use variables and strings in a print, it can get irritating to keep concatenating and keeping the whitespaces and commas in mind:

System.out.println("The sum of " + i + " and " + j + " is " + (i+j));

  • A printf, can make things easier:

System.out.printf("The sum of %d and %d is %d", i, j, (i+j));

Formatter Class

  • The java.util.Formatter is the class that contains all the string format functionality through it's format() methods.
  • System.out.printf()/System.out.format()/String.format() etc all utilize the Formatter class.
  • A formatter can be constructed with output sources such as a StringBuffer, a File or an OutputStream.
  • Example here is a formatter, writing to a file:
                File piFile = new File("/tmp/pi.txt");
		System.out.println("Created file");
		Formatter f2 = new Formatter(piFile);
		f2.format("The value of PI rounded to %d decimals is %.3f", 3, Math.PI);
		System.out.println("Formatted to file");

Format String

  • Syntax:

%[arg_index$][flags][width][.precision] conversion_char

  • Every argument must have a format string in the above syntax, or it wont be printed!

Arguments within [] are optional. Only the conversion_char is mandatory. The following are the basic conversion chars:

  • b - boolean
  • c - char
  • d - integer
  • f - floating point
  • s - string
  • n - line separator

There are many more conversion chars for each data type:

  • Integers have o, x for octal/hex.
  • Floats have e (scientific), g, A - esoteric usage.

Optional arguments

  • arg_index is the number of the argument followed by a $. The no starts from 1.
  • example:
System.out.printf("%2$s , %1$s", "Suhrid", "Karthik");
//Prints : Karthik, Suhrid
  • flags
    • "-" : Left justify
    • "+" : Include a sign
    • "0" : Pad with zeroes
    • "," : Use locale specific group separators
    • "(" : Enclose -ve numbers in brackets
  • examples:
int i = 11;
int j = -22;
out.printf("%+d , %+d", i, j);
//prints: +11 , -22
  • Some flags require width to be mandatory - e.g. left-justify and zero-pad.
  • width indicates the minimum number of characters to print.
out.printf("%3d", 101231);
//prints 101231.

out.printf("%5d", 17);
//prints "   17"

  • Finally the precision - a number prefix with a ".". This is to indicate the number of digits to print after a decimal point. This applies only to floats.
  • The format() method is very strict about data types. It will not try to format float as int or int as float etc. A java.util.IllegalFormatConversionException will be thrown.
  • There is a whole bunch of runtime exceptions associated with string formating. All are subclasses of IllegalFormatException.

e.g. IllegalFormatFlagsException, IllegalFormatPrecisionException etc. etc.

  • Note that Some of the output can be written by format and then the exception can be thrown mid-way.