Java System.out.format examples

System.out.format method format multiple arguments based on format string.

Basic example

public class Main {
  public static void main(String[] args) {
    int int1 = 10;
    double double1 = 10.2;
    String str1 = "Hello";
    System.out.format("%d %f %s\n", int1, double1, str1);
  }
}
OpenJDK 64-Bit Server VM warning: Insufficient space for shared memory file:
   7909
Try using the -Djava.io.tmpdir= option to select an alternate temp location.

print integer 8 characters in width

public class Main2 {
  public static void main(String[] args) {
    int int1 = 245;
    System.out.format("%8d\n",int1);    // Min 8 character width. Pad with space if needed
    System.out.format("%08d\n",int1);  // Min 8 character width. Pad with 0 if needed
  }
}
OpenJDK 64-Bit Server VM warning: Insufficient space for shared memory file:
   7921
Try using the -Djava.io.tmpdir= option to select an alternate temp location.

print float with 2 digits after decimal point

public class Main3 {
  public static void main(String[] args) {
    double double1 = 10.2456;
    System.out.format("%.2f\n",double1);
  }
}
OpenJDK 64-Bit Server VM warning: Insufficient space for shared memory file:
   7933
Try using the -Djava.io.tmpdir= option to select an alternate temp location.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments