No announcement
 

Accessing Array Elements

The array elements are numbered starting from 0. i.e, the first element is numbered 0, second element is numbered 1, and so on.

To access an specific array element , simply specify the index of the element or we can use a counter variable to loop on all elements.

Example:

ArraysDemo.java

package com.codingnous.tutorial;

public class ArraysDemo {

	public static void main(String[] args) {
		// Declaring arrays in two ways.
		int[] numberArray = new int[5];
		int otherArray[] = new int[5];

		// Declaring and initializing array
		int[] initialArray = { 20, 12, 40, 50, 8 };

		// Setting value in array after declaration.
		numberArray[0] = 5;
		otherArray[2] = 35;

		// Accessing array element.
		System.out.println("Value at index 0 in numberArray: " + numberArray[0]);
		System.out.println("Value at index 2 in otherArray: " + otherArray[2]);

		// Accessing array elements using for loop.
		System.out.println("\nAccessing initialArray:");
		for (int counter = 0; counter < initialArray.length; counter++) {
			System.out.println("Value at index " + counter + " is " + initialArray[counter]);
		}

		// You can also use enhanced for loop.
	}
}

Output
Value at index 0 in numberArray: 5 Value at index 2 in otherArray: 35 Accessing initialArray: Value at index 0 is 20 Value at index 1 is 12 Value at index 2 is 40 Value at index 3 is 50 Value at index 4 is 8