Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int with leading 0's behave strangely [duplicate]

Tags:

java

int

Possible Duplicate:
Integer with leading zeroes

Can someone please tell me what is going on here? When I initialize an int with leading zeroes the program does not ignore the zeroes and instead does some other operation I am unaware of.

int num = 0200;

System.out.println(num); // 128

System.out.println(033); // 27
like image 863
Andrew Avatar asked Dec 03 '22 07:12

Andrew


2 Answers

Sure - it's treating it as an octal literal, as per the Java Language Specification, section 3.10.1:

An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 and can represent a positive, zero, or negative integer.

OctalNumeral:
        0 OctalDigits

OctalDigits:
        OctalDigit
        OctalDigit OctalDigits

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

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.

like image 200
Jon Skeet Avatar answered Dec 18 '22 11:12

Jon Skeet


That's an octal (base 8) literal.

Similarly, 0x27 is a hexadecimal (base 16) literal, with a decimal value of 39.

like image 37
SLaks Avatar answered Dec 18 '22 12:12

SLaks