Author Topic: Array Indices start with zero  (Read 3494 times)


  • Moderator
  • User
  • *****
  • Posts: 85
Array Indices start with zero
« on: January 23, 2006, 02:15:38 AM »
In Java, the indices of arrays always start with zero.  They never start with 1 or any other number other than 0.  This means that the last index number is one less than the length of the array.

In a situation in which you normally think in terms of some other numbering scheme, you might need to adjust your code to reconcile the array indices with intuitve numbering.  For example you might want to think of the data stored in the array as being numbered starting with 1.  If say, the company's employees are numbered starting with 1, you might use such as the following in a payroll program:
Code: [Select]

int[] hours = new int[100];
System.out.println("Enter hours worked for each employee: ");

for (int index = 0; index < hours.length; index++)
     System.out.println("Enter hours for employee " + (index + 1);
     hours[index] = keyboard.nextInt();

With this code, employees are numbered from 1 to 100, but their hours worked are stored in elements hours[0] through hours[99].

Reference: Java- An Intro to Comp. Sci & Programming 3/e (Savitch)
Analyze. Design. Develop. Debug. Deploy. Maintain.