Arrays in Java – Declaration, Initialization and Examples
An array stores a fixed number of values of the same type in one variable. Instead of declaring mark1, mark2 … mark50, you create one array of 50 marks and reach each one by its position, called its index.
Arrays are the most basic data structure in Java and the foundation of many others, including ArrayList. This tutorial covers declaring, creating and initialising arrays, reading and writing elements, default values, looping, the Arrays helper class, and common pitfalls.
1. What Is an Array?
Think of an array as a row of numbered lockers. All lockers are the same size (same type), the row has a fixed length, and each locker is opened by its number, starting from 0.
- Same type: an
int[]holds onlyintvalues; aString[]holds only strings. - Fixed size: the length is set when the array is created and never changes.
- Zero-based indexes: the first element is at index 0, the last at
length - 1. - Fast access: reading or writing any element by index takes constant time.
- Arrays are objects: they live on the heap, have a
lengthfield and can benull.
2. Declaring, Creating and Initialising
int[] a; // declaration only (a is not created yet)
a = new int[5]; // creation: 5 elements, all 0
int[] b = new int[5]; // declaration + creation
int[] c = {10, 20, 30}; // declaration + initialisation (size 3)
int[] d = new int[] {10, 20, 30}; // same, also usable outside a declaration
int e[] = new int[3]; // C-style brackets are legal but discouraged
public class ArrayBasics {
public static void main(String[] args) {
// 1. Declare and create: 5 slots, all set to the default value 0
int[] marks = new int[5];
// 2. Assign values by index (0 to length - 1)
marks[0] = 78;
marks[1] = 92;
marks[2] = 65;
marks[3] = 88;
marks[4] = 71;
// 3. Read values
System.out.println("First mark: " + marks[0]);
System.out.println("Last mark: " + marks[marks.length - 1]);
System.out.println("Length: " + marks.length);
// Declare, create and initialise in one step
String[] days = {"Mon", "Tue", "Wed"};
for (String d : days) System.out.print(d + " ");
System.out.println();
}
}
First mark: 78 Last mark: 71 Length: 5 Mon Tue Wed
3. Default Values and Printing
When an array is created with new, every element gets the default value of its type. To print an array's contents, use Arrays.toString(); printing the array directly shows only its type and a hash code.
import java.util.Arrays;
public class ArrayDefaults {
public static void main(String[] args) {
System.out.println("int[]: " + Arrays.toString(new int[3]));
System.out.println("double[]: " + Arrays.toString(new double[3]));
System.out.println("boolean[]: " + Arrays.toString(new boolean[3]));
System.out.println("char[]: " + Arrays.toString(new char[3]).replace('\u0000', '0') + " (the \\u0000 character)");
System.out.println("String[]: " + Arrays.toString(new String[3]));
int[] data = {1, 2, 3};
System.out.println("println(array) prints: " + (data.toString().startsWith("[I@") ? "[I@... (type and hash code)" : data));
System.out.println("Arrays.toString: " + Arrays.toString(data));
}
}
int[]: [0, 0, 0] double[]: [0.0, 0.0, 0.0] boolean[]: [false, false, false] char[]: [0, 0, 0] (the \u0000 character) String[]: [null, null, null] println(array) prints: [I@... (type and hash code) Arrays.toString: [1, 2, 3]
4. Looping Over Arrays
Use a classic for loop when you need the index, and a for-each loop when you only need the values:
for (int i = 0; i < marks.length; i++) {
System.out.println("Student " + (i + 1) + ": " + marks[i]);
}
for (int m : marks) {
System.out.println(m);
}
5. Common Operations and the Arrays Class
The java.util.Arrays class provides ready-made helpers for sorting, searching, copying, filling and comparing arrays:
import java.util.Arrays;
public class ArrayOperations {
public static void main(String[] args) {
int[] scores = {72, 95, 58, 81, 64};
int sum = 0, max = scores[0];
for (int s : scores) {
sum += s;
if (s > max) max = s;
}
System.out.println("sum = " + sum + ", average = " + (double) sum / scores.length + ", max = " + max);
int[] sorted = scores.clone(); // copy before sorting
Arrays.sort(sorted);
System.out.println("sorted: " + Arrays.toString(sorted));
System.out.println("original: " + Arrays.toString(scores));
System.out.println("index of 81 in sorted: " + Arrays.binarySearch(sorted, 81));
int[] bigger = Arrays.copyOf(scores, 7); // resize by copying
System.out.println("copyOf to 7: " + Arrays.toString(bigger));
int[] filled = new int[4];
Arrays.fill(filled, 9);
System.out.println("fill(9): " + Arrays.toString(filled));
System.out.println("equals: " + Arrays.equals(scores, scores.clone()));
System.out.println("stream sum: " + Arrays.stream(scores).sum());
}
}
sum = 370, average = 74.0, max = 95 sorted: [58, 64, 72, 81, 95] original: [72, 95, 58, 81, 64] index of 81 in sorted: 3 copyOf to 7: [72, 95, 58, 81, 64, 0, 0] fill(9): [9, 9, 9, 9] equals: true stream sum: 370
| Method | Purpose |
|---|---|
Arrays.toString(a) | Readable text of the elements. |
Arrays.sort(a) | Sorts in ascending order (in place). |
Arrays.binarySearch(a, key) | Finds a value in a sorted array. |
Arrays.copyOf(a, n), copyOfRange | Copies into a new array of another size. |
Arrays.fill(a, v) | Sets every element to v. |
Arrays.equals(a, b) | Compares contents. |
Arrays.stream(a) | Processes elements with streams. |
Arrays.asList(...) | Fixed-size list view of an object array. |
See Arrays class in Java for more.
6. Common Pitfalls
import java.util.Arrays;
public class ArrayPitfalls {
public static void main(String[] args) {
int[] nums = {10, 20, 30};
// Index out of range
try {
System.out.println(nums[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
}
// Arrays are objects: assignment copies the reference
int[] alias = nums;
alias[0] = 99;
System.out.println("nums after changing alias: " + Arrays.toString(nums));
// == compares references, Arrays.equals compares contents
int[] same = {99, 20, 30};
System.out.println("nums == same: " + (nums == same) + ", Arrays.equals: " + Arrays.equals(nums, same));
// The size is fixed after creation
System.out.println("length stays " + nums.length + "; use ArrayList for a growable list");
}
}
Error: Index 3 out of bounds for length 3 nums after changing alias: [99, 20, 30] nums == same: false, Arrays.equals: true length stays 3; use ArrayList for a growable list
- Accessing index
lengthor a negative index throwsArrayIndexOutOfBoundsException. - Assigning one array variable to another copies the reference; use
clone()orArrays.copyOf()for a real copy. ==compares references; useArrays.equals()to compare contents.- Arrays cannot grow; use an
ArrayListwhen the size changes. - Arrays use the field
length; strings use the methodlength(); collections usesize().
7. Types of Arrays
- Single-dimensional arrays: a simple list of values.
- Multidimensional arrays: arrays of arrays, such as tables and matrices.
- Jagged arrays: 2D arrays whose rows have different lengths.
- Anonymous arrays: arrays created without a variable name.
8. Array vs ArrayList
| Feature | Array | ArrayList |
|---|---|---|
| Size | Fixed | Grows automatically |
| Primitives | Yes (int[]) | No, uses wrappers (Integer) |
| Length | arr.length | list.size() |
| Methods | Through the Arrays class | Built in (add, remove, contains…) |
| Performance and memory | Slightly better | Slight overhead |
9. Summary
- An array holds a fixed number of elements of one type, accessed by indexes from 0 to
length - 1. - Create arrays with
new type[size]or an initializer{...}; new elements get default values. - Arrays are objects: assignment copies references, and
==compares references. - The
Arraysclass sorts, searches, copies, fills, compares and prints arrays. - Use an ArrayList when you need a size that can change.