Hosted Forum: West Visayas State University - Philippines > Object Oriented Programming with Java Class Forum

Array Indices start with zero

(1/1)

louiecerv:
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: ---
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();
}

--- End code ---


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)

Navigation

[0] Message Index

Go to full version