Arrays in Java
Site Admin
· 11 Sep 2026
· 12 views
What Is an Array?
An array is a fixed-size container that stores many values of the same type at consecutive memory positions. Each slot is reached by an index starting at 0.
Creating Arrays
int[] numbers = new int[5]; // 5 slots, all zero
int[] known = {10, 20, 30, 40}; // initialised directly
String[] names = new String[]{"A", "B", "C"};Reading and Writing
int[] scores = new int[3];
scores[0] = 90;
scores[1] = 85;
scores[2] = 78;
System.out.println(scores[1]); // 85
System.out.println(scores.length); // 3 (number of slots)The ArrayIndexOutOfBounds Error
int[] a = {1, 2, 3};
System.out.println(a[5]); // runtime exception: index 5 is invalidJava checks indexes at runtime, so accessing a slot outside the array throws ArrayIndexOutOfBoundsException instead of corrupting memory.
Two-Dimensional Arrays
int[][] grid = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(grid[1][2]); // 6Looping Over an Array
int[] nums = {3, 7, 2};
for (int value : nums) {
System.out.println(value);
}Copying Arrays
int[] original = {1, 2, 3};
int[] copy = java.util.Arrays.copyOf(original, original.length);
// modify copy without touching original


- Indexes start at 0;
lengthgives the size. - Array size is fixed once created.
- Invalid indexes throw
ArrayIndexOutOfBoundsExceptionat runtime.