PrintfDemo.java

Download PrintfDemo.java

 1: // PrintfDemo.java - a demo that shows how to format using printf.
 2: // (Prior to Java 5 we used legacy classes such as NumberFormatter.)
 3: //
 4: // See Java API docs for java.util.Formatter class for details on
 5: // the syntax of the "format" string used with printf.  In brief,
 6: // for each argument after the required format string, those arguments
 7: // will be substituted into the format string using a "conversion":
 8: //   %b  a boolean
 9: //   %c  a character
10: //   %s  a string
11: //   %d  an integer (including BigInteger objects)
12: //   %o  an integer, in octal
13: //   %h  an integer, in hexadecimal ("%H" is the same but with uppercase)
14: //   %f  a floating point value
15: //   %n  an end-of-line character sequence (platform-specific)
16: //   %%  a literal percent symbol
17: //
18: //  (Between the '%' and the letter indicating the type of conversion,
19: //  various optional flags can appear.)
20: //
21: // Written 1/2005 (updated 3/2019) by Wayne Pollock, Tampa Florida USA.
22: 
23: class PrintfDemo
24: {
25:     public static void main ( String [] args )
26:     {
27:         double someDbl = 3.6666666665;
28:         int someInt = 26;
29:         int someOtherInt = 66;
30:         boolean someBool = true;
31:         char someChar = 'A';
32:         String someString = "Hymie";
33: 
34:         System.out.println( "original double:  "  + someDbl );
35:         System.out.println( "original int:     "  + someInt );
36:         System.out.println( "original boolean: "  + someBool );
37:         System.out.println( "original char:    "  + someChar );
38:         System.out.println( "original string:  "  + someString );
39: 
40:         System.out.printf( "%n\t---Using printf:---%n%n" );
41: 
42:         System.out.printf( "double: %%f=%f, %%5.2f=%5.2f, %%05f=%05f, "
43:            + "%%05.2f=%05.2f, %%e=%4.1e %n%n", someDbl, someDbl,
44:             someDbl, someDbl, someDbl );
45: 
46:         System.out.printf( "int: %%d=%d, '%%5d'='%5d', '%%-5d'='%-5d', "
47:            + "%%o=%o, %%h=%h, %%H=%H, %%c=%c %n%n", someInt, someInt, someInt,
48:            someInt, someInt, someInt, someInt );
49:         System.out.printf( "other int: %%d=%d, %%c=%c %n%n", someOtherInt,
50:            someOtherInt );
51: 
52:         System.out.printf( "char: %%c=%c %n%n", someChar );
53: 
54:         System.out.printf( "string (%%S):    My name is '%S'.%n", someString );
55:         System.out.printf( "string (%%10s):  My name is '%10s'.%n", someString );
56:         System.out.printf( "string (%%-10s): My name is '%-10s'.%n%n",
57:             someString );
58: 
59:         System.out.printf( "boolean: '%%-5b'='%-5b', '%%-5B'='%-5B' %n%n",
60:            someBool, someBool );
61: 
62:         System.out.printf( "hashcode: %%h=%h %n", new Object() );
63:     }
64: }