2

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!?

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

7 Comments

It's ancient, I am not sure but I think this should have been there since day one. But with no concrete evidence (JLS 1.0) I really can't say for sure.
Hexa starts with 0x, binary with 0b (binary literals started in Java 7). But octal literals I can't find in documentation: docs.oracle.com/javase/tutorial/java/nutsandbolts/…
It's rather strange that that page mentions nothing about octal literals. Also the knowledge of binary literal is nice,
That's not documentation - it's a tutorial. You can read the link for JLS I gave in the answer and search for octal. Just edited answer too.
Well that's a bug in the tutorial. I think there are quite a handful of them, so yo could just give them a feedback by clicking the link in the bottom. But JLS is the ultimate reference in any Java related matters.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.