Why are integer literals with leading zeroes interpreted strangely?

Solution 1:

A leading zero denotes that the literal is expressed using octal (a base-8 number).

0123 can be converted by doing (1 * 8 * 8) + (2 * 8) + (3), which equals 83 in decimal. For some reason, octal floats are not available.

Just don't use the leading zero if you don't intend the literal to be expressed in octal.

There is also a 0x prefix which denotes that the literal is expressed in hexadecimal (base 16).

Solution 2:

Because integer literals starting with 0 are treated as octal numbers.

See section 3.10.1 of the JLS

Solution 3:

Try this:

public static String leftPad(int n, int padding) {
    return String.format("%0" + padding + "d", n);
}
leftPad(5, 3); // return "005"
leftPad(15, 5); // return "00015"
leftPad(224, 3); // return "224"
leftPad(0, 4); // return "0000"

Solution 4:

first one printed as 83 because java takes 0123 as octal number and it prints decimal equivalent of that number.

Solution 5:

The octal (leading 0) and hexadecimal (leading 0x) were inherited from C. For comparison, try

System.out.println(0x123);