Java

 

 

 

 

Java - printf

 

 

printf() in Java has almost same functionality and usage as printf in C. I think the example below would show you almost all the case of printf format indicator. You don't need to memorize all these format, just copy an example shown here and past it in your code whenever you need it.

 

printf01.java

public class printf01 {

 

    public static void main(String[] args) {

 

        int d = 123;

        float f = 123.45f;

 

        System.out.printf("%d\n",d) ;

        System.out.printf("%8d\n",d) ;

        System.out.printf("%08d\n",d) ;

        System.out.printf("%x\n",d) ;

        System.out.printf("0x%x\n",d) ;

        System.out.printf("%#x\n",d) ;

        System.out.printf("0x%8x\n",d);

        System.out.printf("%#10x\n",d)  ;

        System.out.printf("0x%08x\n",d) ;

        System.out.printf("%#010x\n",d) ;

        System.out.printf("%#X\n",d) ;

        System.out.printf("0x%8X\n",d) ;

        System.out.printf("%#10X\n",d)  ;

        System.out.printf("0X%08X\n",d) ;

        System.out.printf("%#010X\n",d) ;

        System.out.printf("%f\n",f) ;

        System.out.printf("%8.2f\n",f) ;

        System.out.printf("%08.2f\n",f) ;

        System.out.printf("%8.3f\n",f) ;

        System.out.printf("%08.3f\n",f) ;

 

    }

 

}

 

 

    C:\temp> java printf01

     

    123          <--- System.out.printf("%d\n",d) ;

         123     <--- System.out.printf("%8d\n",d) ;

    00000123     <--- System.out.printf("%08d\n",d) ;

    7b           <--- System.out.printf("%x\n",d) ;

    0x7b         <--- System.out.printf("0x%x\n",d)

    0x7b         <--- System.out.printf("%#x\n",d) ;

    0x      7b   <--- System.out.printf("0x%8x\n",d);

          0x7b   <--- System.out.printf("%#10x\n",d)  ;

    0x0000007b   <--- System.out.printf("0x%08x\n",d) ;

    0x0000007b   <--- System.out.printf("%#010x\n",d) ;

    0X7B         <--- System.out.printf("%#X\n",d) ;

    0x      7B   <--- System.out.printf("0x%8X\n",d) ;

          0X7B   <--- System.out.printf("%#10X\n",d)  ;

    0X0000007B   <--- System.out.printf("0X%08X\n",d) ;

    0X0000007B   <--- System.out.printf("%#010X\n",d) ;

    123.449997   <--- System.out.printf("%f\n",f) ;

      123.45     <--- System.out.printf("%8.2f\n",f) ;

    00123.45     <--- System.out.printf("%08.2f\n",f) ;

     123.450     <--- System.out.printf("%8.3f\n",f) ;

    0123.450     <--- System.out.printf("%08.3f\n",f) ;