Java Tutorial/Development/printf Method

Материал из Java эксперт
Перейти к: навигация, поиск

Содержание

a one-or-two-digit day of the month: %te/%Te

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("a one-or-two-digit day of the month: %te/%Te\n", now, now);
 }

}</source>



a one-or-two-digit day of the month: 24/24


Conversion characters for date

   <source lang="java">

import java.util.Calendar; public class MainClass {

  public static void main( String args[] ) 
  {
     Calendar dateTime = Calendar.getInstance();
   
     System.out.printf( "%1$tA, %1$tB %1$td, %1$tY\n", dateTime );
     System.out.printf( "%1$TA, %1$TB %1$Td, %1$TY\n", dateTime );
     System.out.printf( "%1$ta, %1$tb %1$te, %1$ty\n", dateTime );
  }
  

}</source>



Thursday, May 24, 2007
THURSDAY, MAY 24, 2007
Thu, May 24, 07


Conversion characters for date/time compositions

   <source lang="java">

import java.util.Calendar; public class MainClass {

  public static void main( String args[] ) 
  {
     Calendar dateTime = Calendar.getInstance();
     
     System.out.printf( "%tc\n", dateTime );
     System.out.printf( "%tF\n", dateTime );
     System.out.printf( "%tD\n", dateTime );
     System.out.printf( "%tr\n", dateTime );
     System.out.printf( "%tT\n", dateTime );
  }
  

}</source>



Thu May 24 16:07:04 PDT 2007
2007-05-24
05/24/07
04:07:04 PM
16:07:04


Conversion characters for time

   <source lang="java">

import java.util.Calendar; public class MainClass {

  public static void main( String args[] ) 
  {
     Calendar dateTime = Calendar.getInstance();
     System.out.printf( "%1$tH:%1$tM:%1$tS\n", dateTime );
     System.out.printf( "%1$tZ %1$tI:%1$tM:%1$tS", dateTime );
  }
  

}</source>



16:07:40
PDT 04:07:40


Decimal: %d

   <source lang="java">

public class MainClass {

   public static void main(String[] args) {
       int n = 1023;
       System.out.printf("Decimal:               %d\n", n);
   }

}</source>



Decimal:               1023


Decimal: %f

   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
   System.out.printf("Decimal:               %f\n", Math.PI);
 }    

}</source>



Decimal:               3.141593


Decimal/Scientific: %g (lower case g)

   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
   System.out.printf("Decimal/Scientific:    %g\n", Math.PI);
 }    

}</source>



Decimal/Scientific:    3.14159


Decimal/Scientific: %G (upper case G)

   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
   System.out.printf("Decimal/Scientific:    %G\n", Math.PI);
 }    

}</source>



Decimal/Scientific:    3.14159


Demonstrate printf()

   <source lang="java">

public class MainClass {

 public static void main(String args[]) {
   System.out.printf("%d %(d %+d %05d\n", 3, -3, 3, 3);
   System.out.printf("Default floating-point format: %f\n", 1234567.123);
   System.out.printf("Floating-point with commas: %,f\n", 1234567.123);
   System.out.printf("Negative floating-point default: %,f\n", -1234567.123);
   System.out.printf("Negative floating-point option: %,(f\n", -1234567.123);
   System.out.printf("Line-up positive and negative values:\n");
   System.out.printf("% ,.2f\n% ,.2f\n", 1234567.123, -1234567.123);
 }

}</source>



3 (3) +3 00003
Default floating-point format: 1234567.123000
Floating-point with commas: 1,234,567.123000
Negative floating-point default: -1,234,567.123000
Negative floating-point option: (1,234,567.123000)
Line-up positive and negative values:
 1,234,567.12
-1,234,567.12


Formated System.out.printf

   <source lang="java">

public class MainClass {

  public static void main( String args[] )
  {
     System.out.printf( "%s\n%s\n", "Welcome to", "Java Programming!" );
  }

}</source>



Welcome to
Java Programming!


Formatting a string and Ouputing to console

   <source lang="java">

public class MainClass {

 public static void main(String[] a) {
   StringBuffer buf = new StringBuffer();
   java.util.Formatter formatter = new java.util.Formatter(buf);
   double x = 27.5, y = 33.75;
   formatter.format("x = %15.2f y = %14.3g", x, y);
   System.out.print(buf);
 }

}</source>



x =           27.50 y =           33.8


Formatting Characters and Strings

   <source lang="java">

public class MainClass {

 public static void main(String[] a) {
   int count = 0;
   for (int ch = "a"; ch <= "z"; ch++) {
     System.out.printf("      %1$4c%1$4x", ch);
     if (++count % 6 == 0) {
       System.out.printf("%n");
     }
     System.out.printf("      %1$4c%<4x", ch);
   }
 }

}</source>



a  61         a  61         b  62         b  62         c  63         c  63         d  64         d  64         e  65         e  65         f  66
f  66         g  67         g  67         h  68         h  68         i  69         i  69         j  6a         j  6a         k  6b         k  6b         l  6c
l  6c         m  6d         m  6d         n  6e         n  6e         o  6f         o  6f         p  70         p  70         q  71         q  71         r  72
r  72         s  73         s  73         t  74         t  74         u  75         u  75         v  76         v  76         w  77         w  77         x  78
x  78         y  79         y  79         z  7a         z  7a


Formatting Data into a String

   <source lang="java">

public class MainClass {

 public static void main(String[] a) {
   double x = 27.5, y = 33.75;
   String outString = String.format("x = %15.2f y = %14.3g", x, y);
   System.out.println(outString);
 }

}</source>



x =           27.50 y =           33.8


Formatting Numerical Data:

   <source lang="java">

public class MainClass {

 public static void main(String[] a) {
   double x = 27.5, y = 33.75;
 
   System.out.printf("x = %f y = %g", x, y);
 }

}</source>



a = 255 b = 5 c = 17


four digit year: %tY/%TY

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("four digit year: %tY/%TY\n", now, now);
 }

}</source>





Hashcode: %h (lower case h)

   <source lang="java">

import java.net.MalformedURLException; import java.net.URL; public class MainClass {

 public static void main(String[] args) throws MalformedURLException {
   URL u = new URL("http://www.jexp.ru");
   
   System.out.printf("hashcode:  %h\n", u);
 }

}</source>



hashcode:  44e3d762


HASHCODE: %H (upper case H)

   <source lang="java">

import java.net.MalformedURLException; import java.net.URL; public class MainClass {

 public static void main(String[] args) throws MalformedURLException {
   URL u = new URL("http://www.jexp.ru");
   System.out.printf("HASHCODE:  %H\n", u);    
 }

}</source>



HASHCODE:  44E3D762


hours and minutes on a 24-hour clock: %tR/%TR

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("hours and minutes on a 24-hour clock: %tR/%TR\n", now, now);
 }

}</source>



hours and minutes on a 24-hour clock: 15:57/15:57


hours, minutes, and seconds on a 12-hour clock: %tr/%Tr

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("hours, minutes, and seconds on a 12-hour clock: %tr/%Tr\n", now, now); 
 }

}</source>



hours, minutes, and seconds on a 12-hour clock: 03:57:55 PM/03:57:55 PM


hours, minutes, and seconds on a 24-hour clock: %tT/%TT

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("hours, minutes, and seconds on a 24-hour clock: %tT/%TT\n", now, now);
 }

}</source>



hours, minutes, and seconds on a 24-hour clock: 15:57:42/15:57:42


ISO tandard date: %tF/%TF

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("ISO 8601 standard date: %tF/%TF\n", now, now);
 }

}</source>



ISO 8601 standard date: 2007-05-24/2007-05-24


Locale-specific morning/afternoon indicator: %tp/%Tp

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("Locale-specific morning/afternoon indicator: %tp/%Tp\n", now, now);
 }

} //</source>



Locale-specific morning/afternoon indicator: am/AM


localized, abbreviated day: %ta/%Ta

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("localized, abbreviated day: %ta/%Ta\n", now, now);
 }

}</source>



localized, abbreviated day: Thu/THU


localized, abbreviated month: %tb/%Tb

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("localized, abbreviated month: %tb/%Tb\n", now, now);
 }

} //</source>



localized, abbreviated month: May/MAY


localized, abbreviated month: %th/%Th

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("localized, abbreviated month: %th/%Th\n", now, now);
 }

} //</source>



localized, abbreviated month: May/MAY


localized day name: %tA/%TA

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("localized day name: %tA/%TA\n", now, now);
 }

}</source>



localized day name: Thursday/THURSDAY


localized month name: %tB/%TB

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("localized month name: %tB/%TB\n", now, now);
 }

} //</source>



localized month name: May/MAY


Lowercase Hexadecimal: %a

   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
   System.out.printf("Lowercase Hexadecimal: %a\n", Math.PI);
 }    

}</source>



Lowercase Hexadecimal: 0x1.921fb54442d18p1


Lowercase hexadecimal: %x

   <source lang="java">

public class MainClass {

   public static void main(String[] args) {
       int n = 1023;
       System.out.printf("%x \n", n);
   }

}</source>



3ff


milliseconds since the epoch: %TQ

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("milliseconds since the epoch: %TQ\n", now);
 }

} //</source>



milliseconds since the epoch: 1178825834349


milliseconds: %tL/%TL

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("milliseconds: %tL/%TL\n", now, now);
 }

} //</source>



milliseconds: 023/023


month/day/year: %tD/%TD

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("month/day/year: %tD/%TD\n", now, now);
 }

}</source>



month/day/year: 05/24/07/05/24/07


nanoseconds: %tN/%TN

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("nanoseconds: %tN/%TN\n", now, now);
 }

} //</source>



nanoseconds: 007000000/007000000


Octal: %o

   <source lang="java">

public class MainClass {

   public static void main(String[] args) {
       int n = 1023;
       System.out.printf("Octal:                 %o\n", n);
   }

}</source>



Octal:                 1777


one-or-two digit hour on a 12-hour: %tl/%Tl

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("one-or-two digit hour on a 12-hour: %tl/%Tl\n", now, now);
 }

} //</source>



one-or-two digit hour on a 12-hour: 11/11


one-or-two digit hour on a 24-hour clock: %tk/%Tk

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("one-or-two digit hour on a 24-hour clock: %tk/%Tk\n", now, now);
 }

} //</source>



one-or-two digit hour on a 24-hour clock: 11/11


output a % character

Because a % sign always indicates the start of a format specifier, you must use "%%" in the format string when you want to output a % character.



   <source lang="java">

public class MainClass {

 public static void main(String[] a) {
   int percentage = 75;
   System.out.printf("\n%1$d%%", percentage);
   String str = "The quick brown fox.";
   System.out.printf("%nThe string is:%n%s%n%1$25s", str);
 }

}</source>



75%
The string is:
The quick brown fox.
     The quick brown fox.


Output URL: %b (lower case b)

   <source lang="java">

import java.net.MalformedURLException; import java.net.URL; public class MainClass {

 public static void main(String[] args) throws MalformedURLException {
   URL u = new URL("http://www.jexp.ru");
   System.out.printf("boolean:   %b\n", u);
 }

}</source>



boolean:   true


Output URL: %B (upper case B)

   <source lang="java">

import java.net.MalformedURLException; import java.net.URL; public class MainClass {

 public static void main(String[] args) throws MalformedURLException {
   URL u = new URL("http://www.jexp.ru");
   System.out.printf("BOOLEAN:   %B\n", u);    
 }

}</source>



BOOLEAN:   TRUE


printf to command line summary

   <source lang="java">

%[argument_index$][flags][width][.precision]conversion

  square brackets is for optional format.
  
  conversion specifying how to display the argument:
    "d": decimal integer 
    "o": octal integer
    "x": hexadecimal integer
    
    "f": decimal notation for float
    "g": scientific notation (with an exponent) for float 
    "a": hexadecimal with an exponent for float
    "c": for a character
    "s": for a string.
    "b": for a boolean value, so its output is "true" or "false".
    "h": output the hashcode of the argument in hexadecimal form.
    "n": "%n" has the same effect as "\n".
                                  
     argument_index: "1$" refers to the first argument, 
                     "2$" refers to the second argument, 
                     "<" followed by $ indicate that the argument should be the same as 
                     that of the previous format specification                    
     
     flags: "-" left-justified
            "^" and uppercase
            "+" output a sign for numerical values.
            "0" forces numerical values to be zero-padded.                                   
     
     width: Specifies the field width for outputting the argument and represents the minimum number of 
            characters to be written to the output.
     
     precision: used to restrict the output depending on the conversion. 
                It specifies the number of digits of precision when 
                outputting floating-point values.</source>
   
  
 
  



Printing a space before non-negative values

   <source lang="java">

public class MainClass {

  public static void main( String args[] )
  { 
     System.out.printf( "% d\n% d\n", 547, -547 );
  }

}</source>



547
-547


Printing numbers with and without the + flag

   <source lang="java">

public class MainClass {

  public static void main( String args[] )
  { 
     System.out.printf( "%d\t%d\n", 786, -786 );
     System.out.printf( "%+d\t%+d\n", 786, -786 );
  }

}</source>



786	-786
+786	-786


Printing with the 0 (zero) flag fills in leading zeros

   <source lang="java">

public class MainClass {

  public static void main( String args[] )
  { 
     System.out.printf( "%+09d\n", 452 );
     System.out.printf( "%09d\n", 452 );
     System.out.printf( "% 9d\n", 452 );
  }

}</source>



+00000452
000000452
      452


Reordering output with argument indices.

   <source lang="java">

public class MainClass {

  public static void main( String args[] ) 
  {
     System.out.printf( 
        "Parameter list without reordering: %s %s %s %s\n", 
        "first", "second", "third", "fourth" );
     System.out.printf( 
        "Parameter list after reordering: %4$s %3$s %2$s %1$s\n", 
        "first", "second", "third", "fourth" );      
  }

}</source>



Parameter list without reordering: first second third fourth
Parameter list after reordering: fourth third second first


RFC 822 numeric time zone indicator: %tz/%Tz

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("RFC 822 numeric time zone indicator: %tz/%Tz\n", now, now);
 }

} //</source>



RFC 822 numeric time zone indicator: -0800/-0800


Right justifying and left justifying values

   <source lang="java">

public class MainClass {

  public static void main( String args[] )
  { 
     System.out.println( "Columns:" );
     System.out.println( "0123456789012345678901234567890123456789\n" );
     System.out.printf( "%10s%10d%10c%10f\n\n", "hello", 7, "a", 1.23 );
     System.out.printf( "%-10s%-10d%-10c%-10f\n", "hello", 7, "a", 1.23 );
  }

}</source>



Columns:
0123456789012345678901234567890123456789
     hello         7         a  1.230000
hello     7         a         1.230000


Right justifying integers in fields: Field Width

   <source lang="java">

public class MainClass {

  public static void main( String args[] )
  { 
     System.out.printf( "%4d\n", 1 );
     System.out.printf( "%4d\n", 12 );
     System.out.printf( "%4d\n", 123 );
     System.out.printf( "%4d\n", 1234 );
     System.out.printf( "%4d\n\n", 12345 ); // data too large 
     System.out.printf( "%4d\n", -1 );
     System.out.printf( "%4d\n", -12 );
     System.out.printf( "%4d\n", -123 );
     System.out.printf( "%4d\n", -1234 ); // data too large 
     System.out.printf( "%4d\n", -12345 ); // data too large 
  }

}</source>



1
  12
 123
1234
12345
  -1
 -12
-123
-1234
-12345


Scientific notation: %e (lower case e)

   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
    System.out.printf("Scientific notation:   %e\n", Math.PI);
 }    

}</source>



Scientific notation:   3.141593e+00


Scientific notation: %E (upper case E)

   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
   System.out.printf("Scientific notation:   %E\n", Math.PI);
 }    

}</source>



Scientific notation:   3.141593E+00


seconds since the epoch: %ts/%Ts

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("seconds since the epoch: %ts/%Ts\n", now, now);
 }

} //</source>



seconds since the epoch: 1178825794/1178825794


Specifying the Width and Precision

   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
   double x = 27.5, y = 33.75;
 
   System.out.printf("x = %15f y = %8g", x, y);
 }

}</source>



x =           27.50 y =           33.8


string: %s (lower case s)

   <source lang="java">

import java.net.MalformedURLException; import java.net.URL; public class MainClass {

 public static void main(String[] args) throws MalformedURLException {
   URL u = new URL("http://www.jexp.ru");
   System.out.printf("string:    %s\n", u);    
 }

}</source>



string:    http://www.jexp.ru


STRING: %S (upper case S)

   <source lang="java">

import java.net.MalformedURLException; import java.net.URL; public class MainClass {

 public static void main(String[] args) throws MalformedURLException {
   URL u = new URL("http://www.jexp.ru");
   System.out.printf("STRING:    %S\n", u);
 }

}</source>



STRING:    HTTP://WWW.jexp.ru


three-digit day of the year: %tj/%Tj

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("three-digit day of the year: %tj/%Tj\n", now, now);
 }

}</source>



three-digit day of the year: 144/144


Time zone abbreviation: %tZ/%TZ

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("Time zone abbreviation: %tZ/%TZ\n", now, now);
 }

} //</source>



Time zone abbreviation: PDT/PDT


two-digit century: %tC/%TC

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("two-digit century: %tC/%TC\n", now, now);
 }

}</source>



two-digit century: 20/20


two-digit day of the month: %td/%Td

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("two-digit day of the month: %td/%Td\n", now, now);
 }

}</source>



two-digit day of the month: 24/24


two digit hour on a 12-hour clock: %tI/%TI

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("two digit hour on a 12-hour clock: %tI/%TI\n", now, now);
 }

} //</source>



two digit hour on a 12-hour clock: 11/11


Two digit hour on a 24-hour clock: %tH/%TH

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("two digit hour on a 24-hour clock: %tH/%TH\n", now, now);
 }

} //</source>



two digit hour on a 24-hour clock: 11/11


two digit minutes ranging from 00 to 59: %tH / %TH

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("two digit minutes ranging from 00 to 59: %tH / %TH\n", now, now);
 }

} //</source>





two-digit month: %tm/%Tm

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("two-digit month: %tm/%Tm\n", now, now);
 }

}</source>



two-digit month: 05/05


two digit seconds ranging from 00 to 60 : %tS/%TS

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("two digit seconds ranging from 00 to 60 : %tS/%TS\n", now, now);
 }

} //</source>



two digit seconds ranging from 00 to 60 : 57/57


two-digit year: %ty/%Ty

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("two-digit year: %ty/%Ty\n", now, now);
 }

}</source>



two-digit year: 07/07


Unix date format: %tc/%Tc

   <source lang="java">

import java.util.Date; public class MainClass {

 public static void main(String[] args) {
   Date now = new Date();
   System.out.printf("Unix date format: %tc/%Tc\n", now, now);
 }

}</source>



Unix date format: Thu May 24 15:58:29 PDT 2007/THU MAY 24 15:58:29 PDT 2007


Uppercase Hexadecimal: %A

   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
   System.out.printf("Uppercase Hexadecimal: %A\n", Math.PI);
 }    

}</source>



Uppercase Hexadecimal: 0X1.921FB54442D18P1


Uppercase hexadecimal: %X

   <source lang="java">

public class MainClass {

   public static void main(String[] args) {
       int n = 1023;
       System.out.printf("%X\n", n);
   }

}</source>



3FF


Using character and string conversion characters.

   <source lang="java">

public class MainClass {

  public static void main( String args[] )
  { 
     char character = "A";
     String string = "This is also a string";
     Integer integer = 1234;  // initialize integer (autoboxing)
     System.out.printf( "%c\n", character );
     System.out.printf( "%s\n", "This is a string" );
     System.out.printf( "%s\n", string );
     System.out.printf( "%S\n", string );
     System.out.printf( "%s\n", integer ); // implicit call to toString
  }

}</source>



A
This is a string
This is also a string
THIS IS ALSO A STRING
1234


Using floating-point conversion characters

   <source lang="java">

public class MainClass {

  public static void main( String args[] )
  { 
     System.out.printf( "%e\n", 12345678.9 );
     System.out.printf( "%e\n", +12345678.9 );
     System.out.printf( "%e\n", -12345678.9 );
     System.out.printf( "%E\n", 12345678.9 );
     System.out.printf( "%f\n", 12345678.9 );
     System.out.printf( "%g\n", 12345678.9 );
     System.out.printf( "%G\n", 12345678.9 );
  }

}</source>



1.234568e+07
1.234568e+07
-1.234568e+07
1.234568E+07
12345678.900000
1.23457e+07
1.23457E+07


Using Java"s printf( ) Method

The printf( ) method automatically uses Formatter to create a formatted string.

The printf( ) method is defined by both PrintStream and PrintWriter.

For PrintStream, printf( ) has these forms:

  1. PrintStream printf(String fmtString, Object ... args)
  2. PrintStream printf(Local loc, String fmtString, Object ... args)

The first version writes args to standard output in the format specified by fmtString, using the default locale.

The second lets you specify a locale.


Using precision for floating-point numbers and strings

   <source lang="java">

public class MainClass {

  public static void main( String args[] )
  { 
     double f = 123.94536; 
     String s = "Happy Birthday"; 
     System.out.printf( "Using precision for floating-point numbers\n" );
     System.out.printf( "\t%.3f\n\t%.3e\n\t%.3g\n\n", f, f, f );  
  
     System.out.printf( "Using precision for strings\n" );
     System.out.printf( "\t%.11s\n", s );
  } // end main 

}</source>



Using precision for floating-point numbers
	123.945
	1.239e+02
	124
Using precision for strings
	Happy Birth


Using the b, B, h, H, % and n conversion characters.

   <source lang="java">

public class MainClass {

  public static void main( String args[] ) 
  {
     Object test = null;
     System.out.printf( "%b\n", false );
     System.out.printf( "%b\n", true );
     System.out.printf( "%b\n", "Test" );
     System.out.printf( "%B\n", test );
     System.out.printf( "Hashcode of \"hello\" is %h\n", "hello" );
     System.out.printf( "Hashcode of \"Hello\" is %h\n", "Hello" );
     System.out.printf( "Hashcode of null is %H\n", test );
     System.out.printf( "Printing a %% in a format string\n" );
     System.out.printf( "Printing a new line %nnext line starts here" );
  }

}</source>



false
true
true
FALSE
Hashcode of "hello" is 5e918d2
Hashcode of "Hello" is 42628b2
Hashcode of null is NULL
Printing a % in a format string
Printing a new line 
next line starts here


Using the comma (,) flag to display numbers with thousands separator

   <source lang="java">

public class MainClass {

  public static void main( String args[] ) 
  {
     System.out.printf( "%,d\n", 58625 );
     System.out.printf( "%,.2f\n", 58625.21 );
     System.out.printf( "%,.2f", 12345678.9 );
  }

}</source>



58,625
58,625.21
12,345,678.90


Using the ( flag to place parentheses around negative numbers

   <source lang="java">

public class MainClass {

  public static void main( String args[] ) 
  {
     System.out.printf( "%(d\n", 50 );
     System.out.printf( "%(d\n", -50 );
     System.out.printf( "%(.1e\n", -50.0 );
  }

}</source>



50
(50)
(5.0e+01)


Using the # flag with conversion characters o and x

   <source lang="java">

public class MainClass {

  public static void main( String args[] )
  { 
     int c = 31;      // initialize c 
  
     System.out.printf( "%#o\n", c );
     System.out.printf( "%#x\n", c );
  }

}</source>



037
0x1f


Using the integral conversion characters

   <source lang="java">

public class MainClass {

  public static void main( String args[] )
  {
     System.out.printf( "%d\n", 26 ); 
     System.out.printf( "%d\n", +26 );
     System.out.printf( "%d\n", -26 );
     System.out.printf( "%o\n", 26 ); 
     System.out.printf( "%x\n", 26 ); 
     System.out.printf( "%X\n", 26 );
  }

}</source>



26
26
-26
32
1a
1A