简体   繁体   中英

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?

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 .

这是因为索引前面的0表示Java认为你正在使用八进制编号系统。

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 (ie 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).

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM