Java Arrays
An array is a container that stores multiple values of the same type in a single variable. Arrays have a fixed size — set at creation and cannot be changed. They're the foundation of data handling in Java, and understanding them is essential before learning Collections.
What is an Array?
Instead of declaring 5 separate variables for 5 marks, you use a single array. Each value is stored at a numbered index starting from 0.
// Without array (tedious)
int mark1 = 85, mark2 = 92, mark3 = 78, mark4 = 88, mark5 = 95;
// With array (clean)
int[] marks = {85, 92, 78, 88, 95};
Declaring and Initializing Arrays
Method 1 — Declare, Then Assign
int[] numbers = new int[5]; // Array of 5 ints (default 0)
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
Method 2 — Direct Initialization
int[] numbers = {10, 20, 30, 40, 50};
// Also valid
String[] fruits = {"apple", "banana", "mango"};
double[] prices = {99.5, 149.99, 49.0};
boolean[] flags = {true, false, true};
Method 3 — new with values
int[] numbers = new int[]{10, 20, 30, 40, 50};
Accessing Array Elements
Use the index in square brackets. Index starts at 0, ends at length - 1.
int[] marks = {85, 92, 78, 88, 95};
System.out.println(marks[0]); // 85 (first)
System.out.println(marks[2]); // 78 (third)
System.out.println(marks[4]); // 95 (last)
// Accessing out of bounds → ArrayIndexOutOfBoundsException
// System.out.println(marks[5]); // ❌ Runtime error
Array indices start at 0, not 1. For an array of length n, valid indices are 0 to n-1. Accessing marks[n] throws ArrayIndexOutOfBoundsException at runtime.
Array Length
Every array has a length property (not a method — no parentheses).
int[] marks = {85, 92, 78, 88, 95};
System.out.println(marks.length); // 5
// Loop using length
for (int i = 0; i < marks.length; i++) {
System.out.println(marks[i]);
}
Iterating Through Arrays
Classic for loop (with index)
int[] marks = {85, 92, 78, 88, 95};
for (int i = 0; i < marks.length; i++) {
System.out.println("Index " + i + ": " + marks[i]);
}
Enhanced for-each loop
for (int mark : marks) {
System.out.println(mark);
}
Reverse iteration
for (int i = marks.length - 1; i >= 0; i--) {
System.out.println(marks[i]);
}
Modifying Array Elements
int[] marks = {85, 92, 78};
marks[0] = 90; // Change first element
marks[2] = 80; // Change third element
System.out.println(marks[0]); // 90
System.out.println(marks[2]); // 80
Common Array Operations
Sum of Array
int[] numbers = {10, 20, 30, 40, 50};
int sum = 0;
for (int num : numbers) {
sum += num;
}
System.out.println("Sum: " + sum); // 150
Find Maximum
int[] numbers = {45, 12, 88, 32, 67};
int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
System.out.println("Max: " + max); // 88
Find Minimum
int[] numbers = {45, 12, 88, 32, 67};
int min = numbers[0];
for (int num : numbers) {
if (num < min) min = num;
}
System.out.println("Min: " + min); // 12
Average
int[] numbers = {10, 20, 30, 40, 50};
int sum = 0;
for (int num : numbers) sum += num;
double avg = (double) sum / numbers.length;
System.out.println("Average: " + avg); // 30.0
Reverse an Array
int[] numbers = {1, 2, 3, 4, 5};
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.print(numbers[i] + " ");
}
// Output: 5 4 3 2 1
Two-Dimensional Arrays (2D)
A 2D array is an array of arrays — like a table with rows and columns.
Declaration
// 3 rows × 4 columns
int[][] matrix = new int[3][4];
// Direct initialization
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Accessing Elements
System.out.println(grid[0][0]); // 1
System.out.println(grid[1][2]); // 6
System.out.println(grid[2][1]); // 8
Iterating 2D Array
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
System.out.print(grid[i][j] + " ");
}
System.out.println();
}
// Output:
// 1 2 3
// 4 5 6
// 7 8 9
Using for-each on 2D Array
for (int[] row : grid) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
Arrays Class (java.util.Arrays)
Java provides a utility class Arrays with many helpful methods.
import java.util.Arrays;
int[] numbers = {5, 2, 8, 1, 9};
// Sort (ascending)
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers)); // [1, 2, 5, 8, 9]
// Fill with value
int[] filled = new int[5];
Arrays.fill(filled, 7);
System.out.println(Arrays.toString(filled)); // [7, 7, 7, 7, 7]
// Copy
int[] copy = Arrays.copyOf(numbers, numbers.length);
// Binary search (array must be sorted)
int index = Arrays.binarySearch(numbers, 5);
System.out.println("Found at: " + index); // 2
// Compare
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(Arrays.equals(a, b)); // true
Array as Method Parameter
public class Demo {
public static int sum(int[] arr) {
int total = 0;
for (int n : arr) total += n;
return total;
}
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
System.out.println(sum(numbers)); // 60
}
}
Real-World Example — Student Report
public class StudentReport {
public static void main(String[] args) {
String[] names = {"Ankit", "Priya", "Rahul", "Sneha"};
int[] marks = {85, 92, 78, 88};
int total = 0;
int highest = marks[0];
String topper = names[0];
for (int i = 0; i < names.length; i++) {
System.out.println(names[i] + ": " + marks[i]);
total += marks[i];
if (marks[i] > highest) {
highest = marks[i];
topper = names[i];
}
}
double average = (double) total / marks.length;
System.out.println("---");
System.out.println("Total: " + total);
System.out.println("Average: " + average);
System.out.println("Topper: " + topper + " (" + highest + ")");
}
}
Arrays vs ArrayList
- Array — fixed size, faster, works with primitives.
- ArrayList — dynamic size, more methods, works with objects only.
Use arrays when size is fixed. Use ArrayList when you need to add/remove items dynamically. We'll cover ArrayList in a future chapter.
For printing an array, always use Arrays.toString(arr). Printing System.out.println(arr) directly shows a memory hash code like [I@1b6d3586, not the contents.
1. Create an array of 5 student marks. Print the average.
2. Find the second largest number in an array.
3. Reverse an array in-place (swap elements).
4. Create a 3×3 matrix and print it in grid format.
5. Sort an array using Arrays.sort() and print it.
Quick Revision
- Arrays store multiple values of the same type.
- Fixed size — set at creation.
- Indices start at 0, end at
length - 1. array.length— no parentheses.- Accessing out-of-bounds →
ArrayIndexOutOfBoundsException. - 2D arrays: array of arrays —
arr[row][col]. Arrays.sort(),Arrays.fill(),Arrays.toString(),Arrays.copyOf().- Use for-each for reading, classic for for indexing.
- Arrays are objects — they have
lengthfield and inherit fromObject.
Interview Questions
Q: What is the default value of array elements?
A: For numeric arrays — 0. For boolean — false. For object arrays (including String) — null.
Q: Difference between array.length and string.length()?
A: array.length is a field (property) — no parentheses. String.length() is a method — needs parentheses. Arrays use .length; Strings use .length().
Q: Can we change the size of an array after creation?
A: No. Java arrays have a fixed size. If you need dynamic sizing, use ArrayList from the Collections framework.
Q: What is ArrayIndexOutOfBoundsException?
A: A runtime exception thrown when you try to access an array with an index outside the valid range (0 to length-1). It's an unchecked exception.
Q: How do you copy an array?
A: Three ways: Arrays.copyOf(arr, arr.length), arr.clone(), or System.arraycopy(). Simple assignment (b = a) doesn't copy — both variables point to the same array.
Q: Difference between 1D and 2D arrays?
A: 1D array is a single list of elements accessed with one index. 2D array is like a table with rows and columns, accessed with two indices arr[row][col]. Internally, 2D arrays are arrays of arrays.
Q: What is a jagged array?
A: An array of arrays where each inner array can have a different length. Example: int[][] jagged = {{1,2}, {3,4,5}, {6}};
Want to Master Java?
Join our Java course in Varanasi — practical classes and career support at our Sarnath centre.