This discussion is archived
2 Replies Latest reply: Oct 22, 2012 10:15 AM by rp0428 RSS

leading zero value

969891 Newbie
Currently Being Moderated
when we store value like
int i = 010;

it will display the output of i as 8.
Why is it so??
  • 1. Re: leading zero value
    TPD-Opitz-Consulting-com Expert
    Currently Being Moderated
    Welcome to the forum.

    http://www.janeg.ca/scjp/lang/literals.html

    numeric literals starting with a '0' are treated als octal numbers.
    hence <tt>010</tt> resolves to:
    <pre> 0*8^2 + 1*8^1 + 0*8^0 = 8</pre>
    bye
    TPD
  • 2. Re: leading zero value
    rp0428 Guru
    Currently Being Moderated
    Welcome to the forum!
    >
    when we store value like
    int i = 010;

    it will display the output of i as 8.
    Why is it so??
    >
    It isn't just 'stored' as an 8 it IS an 8. It is displayed as decimal so, as an 8 it displays as decimal 8.

    Your question is really why is 010 stored as an 8. The answer to that can be found in The Java Language Specification
    http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.1

    Section 3.10.1 Integer Literals has your answer. You should read then entire section but this is the spec that applies
    >
    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.

    OctalNumeral:
    0 OctalDigits
    0 Underscores OctalDigits

    OctalDigits:
    OctalDigit
    OctalDigit OctalDigitsAndUnderscoresopt OctalDigit

    OctalDigit: one of
    0 1 2 3 4 5 6 7

    OctalDigitsAndUnderscores:
    OctalDigitOrUnderscore
    OctalDigitsAndUnderscores OctalDigitOrUnderscore

    OctalDigitOrUnderscore:
    OctalDigit
    _

    Note that octal numerals always consist of two or more digits; 0 is always considered to be a decimal numeral - not that it matters much in practice, for the numerals 0, 00, and 0x0 all represent exactly the same integer value.
    >
    Then, as TPD showed, octal 010 is decimal 8.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points