ceklock
ceklock

Reputation: 6372

Unexpected int/Integer behavior when number starts by 0

I can't understand why this is not printing the expected value (400300) when I put extra zeros in front of the number:

System.out.println(new Integer(0400300)); // prints 131264
System.out.println(0400300); // prints 131264

If I put one or more zeros in front of the number, the expected value is not printed.

// JUnit test does not pass:
assertTrue(0400300 == 400300);  // returns false!?

Upvotes: 2

Views: 597

Answers (1)

zw324
zw324

Reputation: 27210

Adding 0 to the front made the number an Octal literal. So:

0400300 = 3 * 8 ^ 2 + 4 * 8 ^ 5 = 131264

See JLS for the relevant sections. Quote:

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.

Upvotes: 10

Related Questions