Difference between revisions of "Formatting"

From Suhrid.net Wiki
Jump to navigationJump to search
Line 71: Line 71:
  
 
out.printf("%3d", 101231);
 
out.printf("%3d", 101231);
//prints 101;
+
//prints 101231.
 +
 
 +
out.printf("%5d", 17);
 +
//prints "  17"
  
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
[[Category:OCPJP]]
 
[[Category:OCPJP]]

Revision as of 02:54, 8 July 2011

Introduction

  • String formatting can be done using the printf() and the format() methods added in java.io.PrintStream (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));


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 conversion chars:

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

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"