1.

Why does the java array index start with 0?

Answer»

It is because the 0 index array avoids the extra arithmetic operation to calculate the MEMORY ADDRESS.

Example - Consider the array and assume each element takes 4-byte memory SPACE. Then the address will be like this -

Now if we want to access index 4. Then internally java calculates the address using the formula-

[Base Address + (index * no_of_bytes)]. So ACCORDING to this. The starting address of the index 4 will be - [100 + (4*4)] = 116. And exactly that's what the address is calculated. 
Now consider the same with 1 index Array -

Now if we apply the same formula here. Then we get - 116 as the starting address of the 4th index. Which is wrong. Then we need to apply formula - [Base Address + ((index-1) * no_of_bytes)].

And for calculating this, an extra arithmetic operation has to be performed. And consider the case where millions of ADDRESSES need to be calculated, this causes complexity. So to avoid this, ) the index array is supported by java.



Discussion

No Comment Found