0

I just wanted to experiment with some integers and assigned the value "0013" to an integer a. When I print the value to the output console I get "11". What causes this? Why I do not get 13 ?

 int b = 0013;
 System.out.println(b);
  • 1
    diuplicate http://stackoverflow.com/questions/473282/how-can-i-pad-an-integers-with-zeros-on-the-left – Sreemat Jan 22 '17 at 11:49
  • it is not a duplicate , I ask "why" .. –  Jan 22 '17 at 11:55
  • @Teo you are correct. –  Jan 22 '17 at 11:58
  • Java has taken over many details from C and C++, including the leading `0` for octal (because digit 0 looks like letter o in octal, I guess) and `0x` for hexadecimal (0 in parallel to octal, x because it is in ‘hex’, I am still guessing). C was designed for low-level programming where particularly hexadecimal numbers were useful, I am not sure whether octal really were or they just thought they were or wanted to include them for completeness. Back in the very old days I have seen octal numbers used on a computer with 6 bit character set. – Ole V.V. Jan 22 '17 at 12:37

2 Answers2

5

A leading zero mean octal. Just like a leading 0x mean hexadecimal

bazza
  • 7,580
  • 15
  • 22
1

Java has accidentally automatically taken your number to be an octal number. Unlike hexadecimal notation, where the number is preceded by a 0x, octal is proceeded by a single zero. The compiler has probably taken your number and made it into an octal format.

Try using 13 instead of 0013

Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
  • 1
    not accidently ... – Artur Jan 22 '17 at 11:49
  • Thanks! That explains everything! –  Jan 22 '17 at 11:49
  • Could I somehow tell the compiler to read the integer as a decimal number? –  Jan 22 '17 at 11:54
  • 1
    @Teo You probably shouldn't. Quote: _Just don't use the leading 0 if you don't mean octal. After all, they are not exactly useful(and programmers who do know about octal numbers will get confused when they see 09F)._ [Source](http://stackoverflow.com/questions/565634/integer-with-leading-zeroes) –  Jan 22 '17 at 11:56