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.
Related Tutorials
Reference: Oracle Java Tutorials: Arrays
Frequently Asked Questions (FAQ)
Q1. What is an array in Java?
An object that holds a fixed number of values of the same type, stored in order and accessed by a zero-based index.
Q2. Why do Java array indexes start at 0?
The index is the offset from the start of the array. The first element is at offset 0. This convention comes from C and makes address calculation simple.
Q3. How do I find the length of an array?
Use the length field (no parentheses): arr.length.
Q4. Can I change the size of an array?
No. The size is fixed at creation. To "resize", create a new array with Arrays.copyOf(), or use an ArrayList.
Q5. What are the default values of array elements?
0 for numeric types, '\u0000' for char, false for boolean and null for reference types.
Q6. What is ArrayIndexOutOfBoundsException?
The exception thrown when you access an index below 0 or greater than or equal to the array's length.
Q7. How do I print an array?
Use Arrays.toString(arr) for one-dimensional arrays and Arrays.deepToString(arr) for multidimensional arrays.
Q8. Are arrays objects in Java?
Yes. Even arrays of primitives are objects on the heap, with a length field and the methods of Object.
Q9. How do I copy an array?
Use arr.clone(), Arrays.copyOf(arr, arr.length) or System.arraycopy(). Plain assignment only copies the reference.
Q10. How do I compare two arrays?
Use Arrays.equals(a, b) for content equality, or Arrays.deepEquals() for nested arrays. == only checks whether they are the same object.
Q11. How do I sort an array?
Arrays.sort(arr) sorts in ascending order. For object arrays, pass a Comparator, such as Arrays.sort(names, Comparator.reverseOrder()).
Q12. Can an array hold different types?
Only through a common supertype, for example an Object[] can hold strings and integers. In practice, arrays usually hold one specific type.
Q13. What is the difference between int[] a and int a[]?
None for a single variable; both declare an int array. int[] a is the preferred Java style because it keeps the type together.
Q14. Can an array have length 0?
Yes, new int[0] is a valid empty array. Returning an empty array instead of null spares callers a null check.
Q15. What is the maximum size of an array?
Indexes are int, so the theoretical limit is about 2.1 billion elements; in practice it is limited by available heap memory (and some JVMs reserve a few slots).
Q16. How do I convert an array to a List?
List.of(arr) for an unmodifiable list, Arrays.asList(arr) for a fixed-size view, or new ArrayList<>(Arrays.asList(arr)) for a fully modifiable list (object arrays only).
Q17. How do I find the largest element in an array?
Loop and track the maximum, or use Arrays.stream(arr).max().getAsInt() for an int[].
Q18. Where are arrays stored in memory?
On the heap. A local array variable on the stack holds only a reference to the array object.
Q19. Should I use an array or an ArrayList?
Use an array for fixed-size data and primitives where memory and speed matter. Use an ArrayList when elements are added or removed and you want built-in methods.
Q20. What does arr.clone() return for arrays of objects?
A shallow copy: a new array containing the same object references. The objects themselves are not copied.