An index in Java refers to an integer value that specifies the position of an element in an array, list, or other ordered data structure. Indices are used to access and modify the elements of an array or list.
In Java, indices are zero-based, meaning that the first element in an array or list has an index of 0, the second element has an index of 1, and so on. For example, to access the third element in an array called myArray
, you would use the index 2
, like this:
int thirdElement = myArray[2];
You can also use indices to modify the elements of an array or list. For example, to set the third element of an array called myArray
to the value 5
, you would use the following code:
myArray[2] = 5;
It's important to note that if you try to access or modify an element of an array or list using an index that is out of bounds (i.e., an index that is greater than or equal to the size of the array or list), you will get an ArrayIndexOutOfBoundsException
.
Here is an example of a simple Java program that demonstrates the use of indices to access and modify the elements of an array:
public class IndexExample { public static void main(String[] args) { int[] myArray = {1, 2, 3, 4, 5}; // Print the second element of the array (index 1) System.out.println(myArray[1]); // Set the fourth element of the array (index 3) to 10 myArray[3] = 10; // Print the entire array for (int i = 0; i < myArray.length; i++) { System.out.print(myArray[i] + " "); } } }
Output:
2 1 10 3 10 5