Difference between revisions of "Formatting"
From Suhrid.net Wiki
Jump to navigationJump to search| Line 1: | Line 1: | ||
== Introduction == | == 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)); | ||
| + | |||
| + | == Format String == | ||
| + | |||
| + | * Syntax: | ||
| + | |||
| + | %[arg_index$][flags][width][.precision] conversion_char | ||
| + | |||
| + | 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. | ||
| + | |||
| + | <syntaxhighlight lang="java5"> | ||
| + | |||
| + | System.out.printf("%2$s , %1$s", Suhrid, Karthik); | ||
| + | //Prints : Karthik, Suhrid | ||
| + | |||
| + | </syntaxhighlight> | ||
[[Category:OCPJP]] | [[Category:OCPJP]] | ||
Revision as of 01:13, 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));
Format String
- Syntax:
%[arg_index$][flags][width][.precision] conversion_char
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.
System.out.printf("%2$s , %1$s", Suhrid, Karthik);
//Prints : Karthik, Suhrid