See the following example:
int a = 0111;
System.out.println(a);
Output: 73
Why is this happening and how can i get the exact value without conversion?
See the following example:
int a = 0111;
System.out.println(a);
Output: 73
Why is this happening and how can i get the exact value without conversion?
According to the Java Language Specification 3.10.1. Integer Literals, there are 4 ways to write an integer literal:
1-9
followed by zero or more digits 0-9
, or the number 0
.0x
followed by one or more hexadecimal digits (0-9
, a-f
). Not case-sensitive.0
followed by one or more digits 0-7
.0b
followed by one or more digits 0
or 1
. Not case-sensitive.(All 4 allow underscores for clarity)
As you can see, the number 111
depends on the prefix:
0111
(OctalNumeral) is 1*8*8 + 1*8 + 1
= 64+8+1
= 73
.
111
(DecimalNumeral) is 1*10*10 + 1*10 + 1
= 100+10+1
= 111
.
0b111
(BinaryNumeral) is 1*2*2 + 1*2 + 1
= 4+2+1
= 7
.
0x111
(HexNumeral) is 1*16*16 + 1*16 + 1
= 256+16+1
= 273
.
Which one is right depends on what you wanted.
Well you're getting the precise value. The problem is the format.
0111
gets interpreted as octal value in java. So your value actually is 73 as a quick calculation would show.
A octal value in java is defined this way:
OctalNumeral:
0 OctalDigits
0 Underscores OctalDigits
So 0_111
would be interpreted in the same way.
The format to use in java code would be:
0b111
Which actually gets interpreted as 7 - in binary format - , as expected.
I'll add the links later on, I'm in a bit of a hurry.