Java Adept
Java Adept

Reputation: 113

Why "010" equals 8?

My simple question is why:

System.out.println(010|4);

prints "12"? I understand bitwise OR operator but why "010" equals 8? It's definitely not compliment 2's notification, so how to decode this number?

Upvotes: 11

Views: 26226

Answers (6)

ShreyashHK
ShreyashHK

Reputation: 13

One point you should consider that the number will be in octal if "0XX" i.e. both X are in range [0,7], otherwise it will result in "Integer number too large".

Upvotes: 0

Anuj Arun Kathavale
Anuj Arun Kathavale

Reputation: 11

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

Upvotes: 1

Reimeus
Reimeus

Reputation: 159844

A leading 0 denotes an octal numeric value so the value 010 can be decoded thus: 010 = 1 * 81 + 0 * 80 = 8

Upvotes: 14

jlordo
jlordo

Reputation: 37823

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.

Upvotes: 12

AllTooSir
AllTooSir

Reputation: 49402

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)

Upvotes: 2

voidMainReturn
voidMainReturn

Reputation: 3517

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.

Upvotes: 2

Related Questions