Array Bounds Basics
Understanding Array Indexing in Java
In Java, arrays are zero-indexed data structures that allow you to store multiple elements of the same type. Understanding array bounds is crucial for preventing runtime errors and writing robust code.
Basic Array Declaration and Initialization
// Declaring and initializing an array
int[] numbers = new int[5]; // Creates an array of 5 integers
String[] fruits = {"Apple", "Banana", "Cherry", "Date", "Elderberry"};
Array Index Range
Arrays in Java have a specific index range that starts from 0 and goes up to (length - 1).
graph LR
A[Array Index Range] --> B[First Element: Index 0]
A --> C[Last Element: Length - 1]
Index Range Example
Consider an array with 5 elements:
Index |
0 |
1 |
2 |
3 |
4 |
Value |
10 |
20 |
30 |
40 |
50 |
Accessing Array Elements
public class ArrayBoundsDemo {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
// Correct access
System.out.println(numbers[0]); // Prints 10
System.out.println(numbers[4]); // Prints 50
// Incorrect access (will cause ArrayIndexOutOfBoundsException)
// System.out.println(numbers[5]); // This would throw an exception
}
}
Key Characteristics of Array Bounds
- Arrays have a fixed size once created
- Indexing starts at 0
- Maximum index is (array length - 1)
- Accessing an index outside this range causes an
ArrayIndexOutOfBoundsException
Best Practices
- Always check array length before accessing elements
- Use array length property to iterate safely
- Implement bounds checking in your code
public void safeArrayAccess(int[] arr, int index) {
if (index >= 0 && index < arr.length) {
System.out.println("Element at index " + index + ": " + arr[index]);
} else {
System.out.println("Index out of bounds");
}
}
By understanding these fundamental concepts of array bounds in Java, developers can write more reliable and error-resistant code. LabEx recommends practicing these principles to improve your Java programming skills.