class test{
public static void main(String args[]){
int a = 011;
System.out.println(a);
}
}
Why I am getting 9
as output instead of 011
?
How can I get 011
as output?
class test{
public static void main(String args[]){
int a = 011;
System.out.println(a);
}
}
Why I am getting 9
as output instead of 011
?
How can I get 011
as output?
The JLS 3.10.1 describes 4 ways to define integers.
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.
The formatting only matters when you print it (or when you convert your
int
to aString
).The formatter
"%03d"
is used to add leading zeroes.Alternatively, you could do it in 1 line, using the
printf
method.A numeric literal that starts with 0 is parsed as an octal number (i.e. radix 8). 011 is 9 in octal.
The
011
is being interpreted as an octal number. This means it's in base 8. See also this SO post. From the accepted answer by Stuart Cook:Digits in Base 10:
100s, 10s, 1s
Digits in Base 8:
64s, 8s, 1s
So the
011
is interpreted as 8+1=9