8

Given the following sample:

public class Main {
    public static void main(String[] args) {
        System.out.println(1234);
        System.out.println(01234);
    }
}

The Output is:

1234
668

Why?

1
  • 1
    Of course Octal prefix - should have known...thanks Nov 24, 2011 at 8:40

4 Answers 4

11

This is because integer literals with a leading zero are octal integers (base 8):

1 * 8^3 + 2 * 8^2 + 3 * 8 + 4 = 668
1
  • if this goes for any numeric literal, would that mean Im not able to convert a string to int without having to convert the octal number to ten-base first, if the strings first number is 0? Thanks Feb 5, 2016 at 15:59
7

This is described in section 3.10.1 of the Java Language Specification. Basically a decimal literal is either just 0, or 1-9 followed by one or more 0-9 characters.

An octal literal is a 0 followed by one or more 0-7 characters.

So 01234 is deemed to be octal.

(Also, interestingly "0" is a decimal literal, but "00" is an octal literal. I can't imagine any situations where that matters, mind you, given that the values are obviously the same.)

1
  • 1
    Heh, Jon Skeet can typo too :) An octal digit is 0-7 only. Nov 24, 2011 at 9:10
4

Leading zero means an octal (base 8) number. 1234 on base-8 is 668.

4

A numeric literal with a leading zero is interpreted as octal, i.e. base 8.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.