How to Access Array Elements in Java: Syntax and Examples
In Java, you access array elements using the
arrayName[index] syntax, where index is the position of the element starting from 0. For example, myArray[0] accesses the first element of the array.Syntax
To access an element in a Java array, use the array name followed by the index in square brackets.
- arrayName: The name of your array variable.
- index: The position of the element you want, starting at 0 for the first element.
Example: arrayName[index]
java
int[] numbers = {10, 20, 30}; int first = numbers[0]; // Accesses the first element (10) int second = numbers[1]; // Accesses the second element (20)
Example
This example shows how to create an array and print each element by accessing it using its index.
java
public class ArrayAccessExample { public static void main(String[] args) { String[] fruits = {"Apple", "Banana", "Cherry"}; System.out.println(fruits[0]); // Prints Apple System.out.println(fruits[1]); // Prints Banana System.out.println(fruits[2]); // Prints Cherry } }
Output
Apple
Banana
Cherry
Common Pitfalls
Common mistakes when accessing array elements include:
- Using an index that is negative or greater than or equal to the array length, which causes
ArrayIndexOutOfBoundsException. - Forgetting that array indexes start at 0, so the last element is at
length - 1.
Example of wrong and right access:
java
int[] nums = {5, 10, 15}; // Wrong: Accessing index 3 (out of bounds) // int wrong = nums[3]; // This will throw ArrayIndexOutOfBoundsException // Right: Accessing last element at index 2 int right = nums[2]; // This is 15
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Array Name | Variable holding the array | int[] arr = {1,2,3}; |
| Index | Position of element starting at 0 | arr[0] accesses first element |
| Access Syntax | Use square brackets with index | arr[1] |
| Index Range | 0 to length-1 | If length=3, valid indexes: 0,1,2 |
| Error | Accessing invalid index throws exception | arr[3] throws ArrayIndexOutOfBoundsException |
Key Takeaways
Use
arrayName[index] to access elements, with index starting at 0.Always ensure the index is within 0 and array length minus one to avoid errors.
Remember the first element is at index 0, not 1.
Accessing an invalid index causes an
ArrayIndexOutOfBoundsException.You can use a loop to access all elements by iterating over valid indexes.