Relative to leading zero in integer value
I have below code
int a = 01111;
System.out.println("output1 = " + a);
System.out.println("output2 = " + Integer.toOctalString(1111));
and output
output1 = 585
output2 = 2127
I expected the output to be as shown below.
output1 = 2127
output2 = 2127
Why does it give 585
when I print the direct int value? I expected java to automatically convert the value with leading zero to octal.
What is the relationship between 01111
and 585
?
source to share
System.out.println("output2 = " +Integer.toOctalString(1111));
Converts a decimal string 1111
in octal string: 2127
.
Octal decimal value 1111
, 585
- as expected, the result is expected, you do not get the same value, because the two operators are doing different things.
The correct test would be:
System.out.println("output2 = " +Integer.toOctalString(a));
Which will give you as expected 1111
source to share
If a numeric literal begins with 0
, it denotes an octal base. Similarly 0x
denotes hexadecimal base and 0b
binary number.
So your
int a=01111;
.. in fact
8^3 + 8^2 + 8^1 + 8^0 =
512 + 64 + 8 + 1 = 585
Integer.toOctalString(1111))
is actually the inverse function, i.e. the result is an octal number which is 1111 decimal, which is 2127
valid
2127(oct) = 2 × 8^3 + 1 × 8^2 + 2 × 8^1 + 7 × 8^0 = 1111(dec)
source to share