Java Arrays
An array is a container that holds a fixed number of values of the same data type. Instead of creating separate variables for each value, an array groups related values together under a single name. Arrays are one of the most fundamental data structures in Java.
Think of an array like a row of numbered boxes — each box holds one value, and each box is identified by its position number (called the index).
Key Characteristics of Arrays
- All elements must be of the same data type.
- The size (length) of an array is fixed once created — it cannot grow or shrink.
- Array indexing starts at 0 (the first element is at index 0).
- Arrays are stored in contiguous memory locations.
Declaring an Array
dataType[] arrayName;Example
int[] scores;
String[] names;
double[] prices;Creating (Allocating) an Array
After declaring, the array must be created using the new keyword and specifying its size:
scores = new int[5]; // array to hold 5 integersOr declare and create in one step:
int[] scores = new int[5];By default, numeric arrays are initialized to 0, boolean arrays to false, and object arrays to null.
Initializing an Array with Values
Values can be assigned directly during declaration using curly braces:
int[] scores = {85, 90, 78, 95, 88};Java automatically determines the array size based on the number of values provided.
Accessing Array Elements
Array elements are accessed using the array name and the index in square brackets.
int[] scores = {85, 90, 78, 95, 88};
System.out.println(scores[0]); // 85 – first element
System.out.println(scores[2]); // 78 – third element
System.out.println(scores[4]); // 88 – fifth (last) elementModifying Array Elements
int[] scores = {85, 90, 78, 95, 88};
scores[2] = 100; // changes the third element from 78 to 100
System.out.println(scores[2]); // 100Array Length
The length property returns the total number of elements in an array.
int[] scores = {85, 90, 78, 95, 88};
System.out.println("Length: " + scores.length); // 5Iterating Over an Array
Using a for Loop
int[] scores = {85, 90, 78, 95, 88};
for (int i = 0; i < scores.length; i++) {
System.out.println("Score at index " + i + ": " + scores[i]);
}Output:
Score at index 0: 85
Score at index 1: 90
Score at index 2: 78
Score at index 3: 95
Score at index 4: 88Using a for-each Loop
int[] scores = {85, 90, 78, 95, 88};
for (int score : scores) {
System.out.println("Score: " + score);
}Example – Finding Maximum Value
int[] numbers = {42, 78, 15, 93, 56};
int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
System.out.println("Maximum: " + max); // 93Example – Calculating Average
int[] marks = {70, 85, 90, 60, 75};
int total = 0;
for (int mark : marks) {
total += mark;
}
double average = (double) total / marks.length;
System.out.printf("Average: %.2f%n", average); // Average: 76.00Multidimensional Arrays
A two-dimensional array is an array of arrays — similar to a table with rows and columns. It is useful for storing data in grid format, like a matrix or a spreadsheet.
Declaration and Initialization
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};Accessing Elements
System.out.println(matrix[0][0]); // 1 – row 0, col 0
System.out.println(matrix[1][2]); // 6 – row 1, col 2
System.out.println(matrix[2][1]); // 8 – row 2, col 1Printing a 2D Array
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.print(matrix[row][col] + "\t");
}
System.out.println();
}Output:
1 2 3
4 5 6
7 8 9 Arrays Class – Utility Methods
The java.util.Arrays class provides helpful methods for working with arrays.
import java.util.Arrays;
int[] nums = {5, 2, 8, 1, 9};
// Sort in ascending order
Arrays.sort(nums);
System.out.println(Arrays.toString(nums)); // [1, 2, 5, 8, 9]
// Fill all elements with a value
Arrays.fill(nums, 0);
System.out.println(Arrays.toString(nums)); // [0, 0, 0, 0, 0]Common Array Mistakes
| Mistake | Error Thrown | Example |
|---|---|---|
| Accessing index out of range | ArrayIndexOutOfBoundsException | scores[10] on an array of size 5 |
| Using array before initialization | NullPointerException | int[] arr; arr[0] = 5; |
| Wrong data type assignment | Compile-time error | int[] arr = {"a", "b"}; |
Summary
- An array stores multiple values of the same type under one name.
- Array indexing starts at 0. The last index is
length - 1. - Arrays have a fixed size once created.
- Use
arrayName.lengthto get the size of an array. - Use
fororfor-eachloops to iterate through array elements. - Two-dimensional arrays represent grid/matrix-style data.
- The
Arraysclass provides utility methods likesort(),fill(), andtoString().
