JDK 1.5 has added format() method in java.lang.String class and provided a printf() method in PrintStream class for printing formatted output in console.
printf() method is similar to C programming language printf() method and allows programmer to print formatting string directly to console, which makes System.out.printf() better alternative of System.out.println() method. Both format() and printf() are overloaded method to support Locale specific formatting.
Formatted String is a String which not only display contents but also display it in a format which is widely accepted like including comma while displaying large numbers e.g. 100,000,000 etc. Displaying formatted String is one of need for modern GUI application.
printf()writes on stdout while format() return you a formatted string.
The printf() provides standard formatted output from the program. This enables programmers to migrate from legacy code.
The following table displays few common formatting codes.
Code | Description |
%s | Formats the argument as a string, usually by calling the toString method on the object. |
%d %o %x | Formats an integer, as a decimal, octal, or hexadecimal Value. |
%f %g | Formats a floating point number. The %g code uses scientific notation. |
%n | Inserts a newline character to the string or stream. |
%% | Inserts the % character to the string or stream. |
Example
public class StringFromatDemo { public static void main(String[] args) { System.out.printf("Integer : %d",20); System.out.printf("Floating point number with 4 decimal digits: %.4f",4.223129391); System.out.printf("Floating point number with 8 decimal digits: %.8f",7.332129394); System.out.printf("String: %s, integer: %d, float: %.6f", "Hello World",77,9.233216); } }
Integer : 20
Floating point number with 4 decimal digits: 4.2231
Floating point number with 8 decimal digits: 7.33212939
String: Hello World, integer: 77, float: 9.233216
Q Which class provides the printf() method?
Ans The java.io.PrintStream class provides the printf() method.
Q What is the Console class?
Ans The Console class has been introduced in Java 6. It provides methods to read input from the console and write output to the console. There is no constructor defined in the Console class. System.Console()method is used to obtain a Console object.
Some of the methods of the Console class are:For example: import java.io.Console; public class NewConsole { public static void main(String[] args) { Console c = System.console(); char[] psw; String name ; psw = c.readPassword("%s", "psw: "); for(char ch: psw) c.format("%c ", ch); // #3: format output c.format(" "); MyConsole obj2 = new MyConsole(); name = c.readLine("%s", "input?: "); c.format("output: %s ", obj2.doStuff(name)); } } class MyConsole { String doStuff(String arg1) { return "result is " + arg1; } }