The JLS 3.10.1 describes 4 ways to define integers.
An integer literal may be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2).
An octal numeral consists of a digit 0 followed by one or more of the digits 0 through 7 ...
A decimal numeral is either the single digit 0, representing the integer zero, or consists of an digit from 1 to 9 optionally followed by one or more digits from 0 to 9 ...
In summary if your integer literal (i.e. 011
) starts with a 0, then java will assume it's an octal notation.
Solutions:
If you want your integer to hold the value 11, then don't be fancy, just assign 11. After all, the notation doesn't change anything to the value. I mean, from a mathematical point of view 11 = 011 = 11,0.
int a = 11;
The formatting only matters when you print it (or when you convert your int
to a String
).
String with3digits = String.format("%03d", a);
System.out.println(with3digits);
The formatter "%03d"
is used to add leading zeroes.
Alternatively, you could do it in 1 line, using the printf
method.
System.out.printf("%03d", a);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…