Java tutorials  /  Java Arrays
Chapter 7 · Java

Java Arrays

An array in Java is a fixed-size, ordered collection of elements of the same data type, stored in contiguous memory locations and accessed using a zero-based index. Once created, an array's size cannot be changed, though the values of its elements can be modified.

Think of an array like a row of numbered lockers in a school hallway, all the same size and shape. Each locker holds exactly one item, and every locker has a number (starting from 0, not 1) that lets you instantly go to that specific locker instead of checking each one from the start. If you have 100 students' names to store, using 100 separate variables would be impractical — an array of size 100 lets you store and access all of them using a single variable name and an index.

Consider a weather monitoring application that records the temperature reading for each of the 24 hours in a day. Instead of creating 24 separate variables (hour0Temp, hour1Temp, ... hour23Temp), a single array 'double[] hourlyTemperatures = new double[24]' stores all readings together. This allows the program to easily calculate the day's average, minimum, and maximum temperature by looping through the array's indices (0 to 23), a pattern used constantly in real applications like sensor data logging, financial time-series analysis, and image processing (where a 2D array often represents pixel grids).

Without arrays, storing and processing multiple related values of the same type would require a separate, individually-named variable for each single value, making it impossible to use loops to process the data efficiently, and impractical for handling large or dynamic datasets like a list of thousands of customer records. Arrays provide a structured, indexed way to group related data together, enabling efficient iteration, sorting, searching, and bulk processing using loops.

  • Single-Dimensional Array: The simplest array form, representing a linear list of elements of the same type, accessed using a single index (e.g., 'int[] scores = new int[5];').
  • Multi-Dimensional Array (2D, 3D, etc.): An array of arrays, most commonly a 2D array used to represent grid-like or tabular data (such as a matrix or a game board), accessed using two indices for rows and columns.
  • Jagged Array: A special form of multi-dimensional array where each inner array (row) can have a different length, unlike a standard rectangular 2D array where every row must have the same number of columns.
// Declaration and instantiation: dataType[] arrayName = new dataType[size]; // Declaration with initialization: dataType[] arrayName = {value1, value2, value3}; // Accessing an element: arrayName[index]; // 2D array declaration: dataType[][] arrayName = new dataType[rows][columns];
A beginner needs to store the marks of 5 students in a single quiz, calculate the total and average marks, and also find the highest score among them — a common task that requires declaring an array, populating it, and traversing it using a loop.
Declaring, Initializing, and Traversing a Single-Dimensional Array
This example creates an array of 5 student marks, then uses a for loop to calculate the total and average score, and identifies the highest mark.
Java
public class StudentMarks { public static void main(String[] args) { int[] marks = {78, 92, 85, 64, 99}; int total = 0; int highest = marks[0]; for (int i = 0; i < marks.length; i++) { total += marks[i]; if (marks[i] > highest) { highest = marks[i]; } } double average = (double) total / marks.length; System.out.println("Total: " + total); System.out.println("Average: " + average); System.out.println("Highest Mark: " + highest); } }
Total: 418 Average: 83.6 Highest Mark: 99
'marks.length' gives the total number of elements in the array (5), which is used as the loop's upper bound to avoid an ArrayIndexOutOfBoundsException. Inside the loop, 'marks[i]' accesses each element by its index, accumulating the sum in 'total' and tracking the largest value seen so far in 'highest'. The average is calculated with an explicit '(double)' cast on 'total' to ensure decimal precision, since dividing two ints would otherwise truncate the result.
Working with a 2D Array (Matrix)
This example declares a 2x3 two-dimensional array representing a simple matrix and uses nested loops to traverse and print all its elements in a grid format.
Java
public class MatrixDemo { public static void main(String[] args) { int[][] matrix = { {1, 2, 3}, {4, 5, 6} }; for (int row = 0; row < matrix.length; row++) { for (int col = 0; col < matrix[row].length; col++) { System.out.print(matrix[row][col] + " "); } System.out.println(); } } }
1 2 3 4 5 6
'matrix.length' gives the number of rows (2), while 'matrix[row].length' gives the number of columns in that specific row (3). The outer loop iterates through each row, and the inner loop iterates through each column within the current row, printing each element followed by a space; 'System.out.println()' with no arguments simply moves to a new line after each row is fully printed, creating the grid-like output format.
  • ArrayIndexOutOfBoundsException from Off-by-One Errors: Since array indices start at 0, the last valid index of an array is always 'length - 1', not 'length'. Writing a loop condition as 'i <= marks.length' instead of 'i < marks.length' attempts to access one index beyond the array's actual bounds, throwing an 'ArrayIndexOutOfBoundsException' at runtime on the final iteration.
  • Confusing Array Length Property with a Method Call: Beginners familiar with String's '.length()' method often mistakenly write 'marks.length()' for an array, forgetting that for arrays, 'length' is a public field, not a method, and should be accessed without parentheses as 'marks.length'. Using parentheses on an array results in a compile-time error.
  • Assuming Arrays Can Be Resized: Once an array is created with a specific size (e.g., 'new int[5]'), that size is permanently fixed and cannot be changed. Beginners sometimes try to add a 6th element to a 5-element array directly, not realizing this requires creating an entirely new, larger array and copying the existing elements over (or using a dynamic-size structure like 'ArrayList' instead, if resizing is a frequent requirement).
  • Shallow Copying an Array with Simple Assignment: Writing 'int[] copy = original;' does not create an independent copy of the array; it merely creates a second reference variable pointing to the exact same underlying array object in memory. Modifying an element through 'copy[0] = 100;' will also change 'original[0]', since both variable names refer to the identical array. A true independent copy requires methods like 'Arrays.copyOf()' or a manual element-by-element loop.
  • Always Use array.length Instead of Hardcoding the Size: When looping through an array, always use 'array.length' as the loop's upper bound condition instead of manually typing the known size (e.g., '5'). This makes the code automatically adapt if the array's size changes later, preventing bugs from an outdated hardcoded number.
  • Use Arrays.toString() for Quick Debugging Output: Instead of manually looping through an array just to print its contents for debugging, use 'java.util.Arrays.toString(arrayName)' (for 1D arrays) or 'Arrays.deepToString(arrayName)' (for 2D arrays), which instantly formats the entire array's contents into a readable String.
  • Consider ArrayList for Dynamic-Size Collections: If the number of elements needed isn't known in advance or needs to grow/shrink during program execution, use 'java.util.ArrayList' instead of a raw array, since ArrayList automatically handles internal resizing, whereas arrays require manual, cumbersome resizing logic.
  • Validate Array Bounds Before Accessing Dynamic Indices: When accessing an array element using an index derived from user input or a calculation (rather than a fixed loop variable), always validate that the index falls within '0' and 'array.length - 1' beforehand, to gracefully handle invalid input rather than letting the program crash with an unhandled exception.
Why do array indices in Java start at 0 instead of 1?
Array indexing starts at 0 because internally, an array's index actually represents an offset from the base memory address where the array begins. Accessing 'array[0]' means 'go to the base address plus zero elements', accessing 'array[1]' means 'go to the base address plus one element's worth of memory', and so on. This zero-based offset approach, inherited from lower-level languages like C, allows for a simple and efficient memory address calculation ('baseAddress + index * elementSize') without needing to subtract 1 every time an element is accessed.
What is the difference between array.length and String.length() in Java?
'array.length' is a public, final field (not a method) that stores the fixed number of elements an array was created with, and is accessed without parentheses (e.g., 'myArray.length'). In contrast, 'String.length()' is a method call (requiring parentheses) defined within the String class that calculates and returns the number of characters in the string. This inconsistency — one being a field, the other a method — is a well-known quirk of Java's design that frequently trips up beginners transitioning between arrays and Strings.
How would you create a true independent copy of an array in Java, and why doesn't simple assignment (=) achieve this?
Simple assignment like 'int[] copy = original;' only copies the reference (memory address) to the array, meaning both 'copy' and 'original' point to the exact same array object in memory — modifying one affects the other. To create a genuinely independent copy, you can use 'int[] copy = java.util.Arrays.copyOf(original, original.length);', which creates a brand new array object and copies each element's value into it, or use 'original.clone()' for a shallow copy of a single-dimensional array. For a deep copy of multi-dimensional or object arrays (where elements are themselves references), each inner array or object must be copied individually as well, since a shallow copy would still share references to the inner arrays/objects.
Write a Java program that declares an array of 6 integers, and prints only the elements at even indices (0, 2, 4).
public class EvenIndexElements { public static void main(String[] args) { int[] numbers = {10, 15, 20, 25, 30, 35}; for (int i = 0; i < numbers.length; i += 2) { System.out.println("Index " + i + ": " + numbers[i]); } } } // Output: // Index 0: 10 // Index 2: 20 // Index 4: 30
What is wrong with the following code, and what exception (if any) will it throw? int[] arr = new int[5]; for (int i = 0; i <= arr.length; i++) { arr[i] = i * 2; }
The loop condition uses 'i <= arr.length' instead of 'i < arr.length'. Since 'arr.length' is 5, valid indices only range from 0 to 4. When 'i' becomes 5 (satisfying 'i <= 5'), the code attempts 'arr[5] = 10;', but index 5 does not exist in a 5-element array (indices 0-4 only), causing an 'ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5' to be thrown at runtime. The fix is to change the condition to 'i < arr.length'.
Write a Java program that creates a 3x3 two-dimensional integer array representing a matrix, fills it with values from 1 to 9 (row by row), and then prints the sum of all elements in the matrix.
public class MatrixSum { public static void main(String[] args) { int[][] matrix = new int[3][3]; int value = 1; int sum = 0; for (int row = 0; row < matrix.length; row++) { for (int col = 0; col < matrix[row].length; col++) { matrix[row][col] = value; sum += value; value++; } } System.out.println("Sum of all elements: " + sum); } } // Output: // Sum of all elements: 45

Arrays are fixed-size, indexed collections that allow Java programs to efficiently store, access, and process multiple values of the same data type using loops, forming the foundation for working with structured datasets like matrices, sensor readings, and lists of records. Understanding zero-based indexing, the fixed nature of array size, the distinction between the 'length' field and 'length()' method, and the difference between shallow reference copies and true independent copies are essential skills for avoiding common runtime errors like ArrayIndexOutOfBoundsException.

© 2026 CompileX. Maintained by Aditya Kumar Sharma.