Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is array indexing in Java start with 0?

Tags:

java

arrays

Why is array indexing done with 0 and not with 1 in programming languages like Java ? I am totally new to java any explanation is welcomed.

like image 842
Shashank Agarwal Avatar asked Jul 19 '14 13:07

Shashank Agarwal


People also ask

Why do we start indexing from 0 in array?

Here, arr denotes the address of the first array element or the 0 index element. So *(arr+i) means the element at i distance from the first element of the array. So array index starts from 0 as initially i is 0 which means the first element of the array.

Is array always start with index 0?

Array index always starts from 0 Programming languages are desinged in a such a way that the array name is always points to the first element of an array.


2 Answers

Java uses zero-based indexing because c uses zero-based indexing. C uses zero-based indexing because an array index is nothing more than a memory offset, so the first element of an array is at the memory it's already pointing to, *(array+0).

See also Wikipedia's array indexing in different languages?

like image 134
Kevin Avatar answered Sep 25 '22 03:09

Kevin


To expand upon @Kevin's answer, I take this quote from an answer on Programmers.SE:

The index in an array is not really an index. It is simply an offset that is the distance from the start of the array. The first element is at the start of the array so there is no distance. Therefore the offset is 0.

Further, if you want to learn more about how different languages do their array indexing, then look at this exhaustive list on Wikipedia.

like image 42
Engineer2021 Avatar answered Sep 24 '22 03:09

Engineer2021