Close

Java String Formatting - How to format integers using String#printf()?

Java String Formatting Java 

This example shows how to format integers with String#printf()

The format specifiers %d is used for this purpose.

Types include: byte, Byte, short, Short, int and Integer, long, Long, and BigInteger

package com.logicbig.example.string;

import java.math.BigInteger;

public class StringPrintfInteger {

public static void main(String[] args) {
System.out.printf("%d%n", 4);
System.out.printf("%d%n", (byte) 4);
System.out.printf("%d%n", -4L);
System.out.printf("%d%n", BigInteger.valueOf(-4L));

//including only one leading space
for (int i = 1; i < 4; i++) {
System.out.printf("[% d]%n", i);
}
}
}

Output

4
4
-4
-4
[ 1]
[ 2]
[ 3]




See Also