Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!?
like image 241
ceklock Avatar asked Feb 11 '26 12:02

ceklock


1 Answers

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.

like image 187
zw324 Avatar answered Feb 15 '26 17:02

zw324