Mob
Mob

Reputation: 11106

Strange array behavior in Java

This is a simple array declaration and initialization.

  int arr[] = new int[10];

    for(int i = 0; i<arr.length; i++){

    arr[i] = i;
    }

This

System.out.println(arr[000001]); 

to

System.out.println(arr[000007]);

prints out the correct values but anything above 8

System.out.println(arr[000008]);

produces a java.lang.RuntimeException: Uncompilable source code

Why does this happen?

Upvotes: 3

Views: 251

Answers (4)

nos
nos

Reputation: 229344

It happens because 000001 , 000007, 000008 is octal notation. Integer literals starting with 0 is treated as octal. However there is no such thing as 000008 in a base 8 numeral system (octal).

(Though, I would have expected that to fail during compile time, not runtime)

Upvotes: 4

It's because the 0's in front of your index make Java think you're using the octal numbering system.

Upvotes: 6

Joachim Sauer
Joachim Sauer

Reputation: 308249

It has nothing to do with arrays.

Integer literals that start with a 0 are expected to be octal numerals.

Therefore, if you have any diggit bigger than 7 (i.e. 8 or 9) in there, then it won't compile.

Also: you only get an Exception because your IDE allows you to execute code that doesn't compile. That's a very bad idea, you should look at the compiler error it produces instead (it will probably have much more information than the message you posted).

Upvotes: 5

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81724

This has nothing to do with arrays; integers starting with the digit 0 are octal (base 8). The legal octal digits are 0-7, so that 08 (or 00000008) are invalid octal integer literals. The correct octal for 8 is 010.

Upvotes: 13

Related Questions