My simple question is why:
System.out.println(010|4);
prints \"12\"? I understand bitwise OR operator but why \"010\" equals 8? It\'s defin
A leading 0
denotes an octal numeric value so the value 010
can be decoded thus: 010 = 1 * 81 + 0 * 80 = 8
Any number in Java which fulfill the below Conditions - A. number Should have three or More Digital B.Number should Start with 0. If above Condition are true then number treated as Octal_Base (8) Number. Therefore, 010=(8^2)*0+(8^1)*1+(8^0)*0=64*0+8*1+1*0=8 So, 010=8
That is because java takes it as an octal literal and hence produces 12. Try System.out.println(10|4)
and the result is 14. Because this time it is taken as decimal literal.
Have a look at the Java Language Specification, Chapter 3.10.1 Integer Literals
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 an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 interspersed with underscores, and can represent a positive, zero, or negative integer.
Now you should understand why 010
is 8
.
As everybody mentioned here that 010
is an Octal Integer literal . The leading 0
specifies that it is an octal representation . Actual value will be :
1*8^1 + 0*8^0 = 8(decimal) = 1000(binary-only last 4 digits)
Now coming back to the SOP :
System.out.println(010|4);
Applying Bitwise OR on 010
and 4
(considering only the last 4 digits) =>
1000|0100
= 1100
= 1*2^3 + 1*2^2 + 0*2^1 + 0*2^0
= 8 + 4 + 0 + 0
= 12(decimal)