Arrays
An array stores a fixed number of values of the same type in numbered slots.
On this page · 5 min · Beginner
On this page
- In simple words
- Learning objectives
- Explanation
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Beginner
- Updated
- Oct 30, 2026
In simple words#
An array is an egg tray: a fixed number of slots, numbered from 0. You can change what’s in a slot, but you cannot add more slots.
- Index
- Slot number starting at 0.
- length
- Number of slots (a field, not a method).
- Arrays utility
- sort, toString, fill, copyOf…
Learning objectives#
- Create and initialise arrays
- Read and write by index
- Use the Arrays utility class
- Choose arrays vs ArrayList
Explanation#
int[] marks = new int[5]; creates five slots with default 0. int[] marks = {78, 92, 65}; creates and fills.
Indexes run from 0 to length - 1. Going outside throws ArrayIndexOutOfBoundsException.
java.util.Arrays has sort, toString, fill, copyOf, binarySearch and asList.
Arrays cannot grow. For a list that changes size, use ArrayList.
Code example: Class marks#
import java.util.Arrays;
int[] marks = {78, 92, 65, 88, 71};
System.out.println("First: " + marks[0] + ", count: " + marks.length);
Arrays.sort(marks);
System.out.println("Sorted: " + Arrays.toString(marks));
int sum = 0;
for (int m : marks) sum += m;
System.out.printf("Average: %.1f%n", (double) sum / marks.length);
int[][] seats = new int[3][4]; // 3 rows × 4 seats
seats[1][2] = 1; // book row 2, seat 3
System.out.println(Arrays.deepToString(seats));
First: 78, count: 5 Sorted: [65, 71, 78, 88, 92] Average: 78.8 [[0, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0]]
This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.
Step-by-step explanation#
- The array literal creates five values.
- Arrays.sort sorts in place.
- printf formats the average to one decimal.
- A 2D array models rows and seats.
Real-world use case#
A cinema booking screen stores seats as a 2D array of booked/free flags.
Common mistakes#
System.out.println(arr) prints something like [I@1b6d3586. Use Arrays.toString.
The last index is length - 1.
Best practices#
- Use ArrayList when size changes
- Arrays.toString for printing
- for-each when the index isn’t needed
- Validate indexes
Remember this#
Index 0 to length - 1.
Fixed size — cannot grow.
Arrays.sort / Arrays.toString.
Practice exercise#
Your task: Find the highest mark in the array.
Show solution
int max = marks[0];
for (int m : marks) if (m > max) max = m;
// or: Arrays.stream(marks).max().getAsInt();
Mini quiz#
What is the index of the last element in an array of length 10?
Want more? Practise all Java MCQs · Java interview questions
My notes#
Saved in this browser.