Array. In Java What is the internal code for length()?

What is stored in the 10th position of the array

int[] array=new int[10];

Suppose we have values stored from array [0] to array [9], if I don't use print elements

array.length()

Or (int a: array)

What should I do?

My basic question is how does the JVM determine the end of the array and whether it encounters null parsing array or garbage value? What is array Built in code of length() function?

Solution

Welcome C / C + + programmers: -)

For arrays, Java uses a different paradigm from C / C + + C / C + + uses the terminator / sentinel (a.k.a. "garbage") value to represent the end of the array In Java, an array is more like a variable length object with a special "instance variable", which indicates how many slots are in the array This special "instance variable" is set when the array is created and is read-only You can say array Length to access it

Java wants the code to know when to stop at the end of the array and make sure they don't specify an index greater than length - however, for security reasons, the JVM checks every access to the array just in case If the JVM finds that the array index is less than 0 or greater than length – 1, the JVM throws indexoutofboundsexception

Since we can always check the length, there is no need to mark the end of an array in Java There is nothing special after the last item in the array (it may be the memory of other variables)

for(int a: array) {
    // code of loop body here
}

This code is magically converted by the compiler to:

for (int i = 0; i < array.length; i++) {
    int a = array[i];
    // code of loop body here
}

However, user code cannot access I index variables This code still implicitly uses array length.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>