1

I observed that in Java when I do this:

public static void main(String[] args){
    int i = 45;
    int j = 045;

    System.out.println("i:>>"+i);
    System.out.println("j:>>"+j);
}

The output is:

i:>>45
j:>>37

Why this is happening? The value of j is printed as 37 when it is 45?

Could anybody please guide? Thanks in advance.

mpontillo
  • 13,559
  • 7
  • 62
  • 90
JavaStudent
  • 1,081
  • 1
  • 8
  • 17

3 Answers3

7

045 is an octal (base 8):

8^2 * 0 + 8^1 * 4 + 5 = 37

45 is a decimal (base 10).


Try running this:

int j = 049;
System.out.println("j:>>" + j);

you will get "The literal 049 of type int is out of range", because octal numbers can just have digits from 0 to 7(this is why it is base 8).

Edit:

As @Gleen mentioned in a comment, an hexadecimal is leading by 0x:

int j = 0x111; // 16^2 * 1 + 16^1 * 1 + 1 = 273
System.out.println("j:>>" + j);

Output:

j:>>273 
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
2

See the Java Language Specification, section 3.10.1.

Quoting:

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
    _

As you'll find if you read the specification, Java also supports several other integer notations, such as hexadecimal (prefix with 0x), and binary (prefix with 0b), as well as plain decimal (no prefix).

mpontillo
  • 13,559
  • 7
  • 62
  • 90
1

When you prefix a literal number in Java with 0, it is treated as an octal value (base 8).

Octal 45 equals 37 in base 10.

Keppil
  • 45,603
  • 8
  • 97
  • 119