Arrays
Suppose you want to store the marks of 60 students. Sixty separate variables (marks1, marks2, ...) would be impossible to manage. An array stores many values of the same type under one name, numbered by position. You can loop over it, sort it and pass it around as a single thing.
In this lesson you will create arrays, read and change their elements, use the helpful java.util.Arrays class, learn why copying an array is not as simple as =, and build two-dimensional arrays for grids such as cinema seating.
Creating and using an array
An array type is written with square brackets: int[] means "array of int". There are two ways to create one:
- With an array literal, when you know the values:
int[] runs = {45, 12, 78}; - With
newand a size, when you will fill it later:double[] prices = new double[3];
Each value in an array is an element, and its position is its index. Indexes start at 0, and length (no brackets) tells you how many elements there are.
public class Basics {
public static void main(String[] args) {
int[] runs = {45, 12, 78, 3, 101}; // array literal
System.out.println("Innings played: " + runs.length);
System.out.println("First innings: " + runs[0]);
System.out.println("Last innings: " + runs[runs.length - 1]);
runs[1] = 21; // correct a scoring mistake
int total = 0;
int best = runs[0];
for (int r : runs) {
total += r;
if (r > best) {
best = r;
}
}
System.out.println("Total: " + total + ", Best: " + best);
System.out.println("Average: " + (double) total / runs.length);
double[] prices = new double[3]; // filled with 0.0
String[] names = new String[2]; // filled with null
boolean[] present = new boolean[2]; // filled with false
System.out.println(prices[0] + " " + names[0] + " " + present[0]);
}
}Innings played: 5 First innings: 45 Last innings: 101 Total: 248, Best: 101 Average: 49.6 0.0 null false
An array created with new is filled with default values: 0 for number types, 0.0 for decimals, false for boolean and null for reference types such as String. Once created, an array's length can never change. If you need a collection that grows and shrinks, use an ArrayList, which you will meet in Collections & Generics.
Reading or writing outside the valid range stops the program. For an array of length 3, a[3] throws:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
The Arrays helper class
The class java.util.Arrays contains ready-made methods for arrays. The most useful are toString (for printing), sort, copyOf, copyOfRange, fill and equals.
import java.util.Arrays;
public class Utils {
public static void main(String[] args) {
int[] marks = {67, 92, 45, 88, 73};
System.out.println(marks); // not useful!
System.out.println(Arrays.toString(marks));
Arrays.sort(marks);
System.out.println(Arrays.toString(marks));
int[] top3 = Arrays.copyOfRange(marks, 2, 5);
System.out.println(Arrays.toString(top3));
int[] bigger = Arrays.copyOf(marks, 7); // extra slots are 0
System.out.println(Arrays.toString(bigger));
String[] cities = {"Pune", "Agra", "Kochi", "Delhi"};
Arrays.sort(cities);
System.out.println(Arrays.toString(cities));
int[] seats = new int[5];
Arrays.fill(seats, -1);
System.out.println(Arrays.toString(seats));
System.out.println(Arrays.equals(new int[]{1, 2}, new int[]{1, 2}));
System.out.println(Arrays.stream(marks).sum());
}
}[I@2ed0fbae [67, 92, 45, 88, 73] [45, 67, 73, 88, 92] [73, 88, 92] [45, 67, 73, 88, 92, 0, 0] [Agra, Delhi, Kochi, Pune] [-1, -1, -1, -1, -1] true 365
Printing an array directly shows something like [I@2ed0fbae: [I means "array of int" and the rest is an internal code that changes from run to run. Always print with Arrays.toString. Arrays.sort sorts numbers from smallest to largest and strings alphabetically, changing the original array. copyOfRange(marks, 2, 5) copies indexes 2 to 4; as with substring, the end index is excluded. The last line gives a taste of streams: Arrays.stream(marks).sum() adds every element without a loop.
Arrays are references
An array is an object, so an array variable holds a reference to it, not the elements themselves. Assigning one array variable to another copies only the reference: both names then point to the same array.
import java.util.Arrays;
public class Alias {
public static void main(String[] args) {
int[] original = {10, 20, 30};
int[] sameArray = original; // copies the reference only
int[] realCopy = original.clone(); // copies the elements
sameArray[0] = 99;
realCopy[1] = 55;
System.out.println(Arrays.toString(original));
System.out.println(Arrays.toString(sameArray));
System.out.println(Arrays.toString(realCopy));
System.out.println(original == sameArray);
}
}[99, 20, 30] [99, 20, 30] [10, 55, 30] true
Changing sameArray[0] also changed original, because they are one array with two names. clone() (or Arrays.copyOf) creates a separate array. This also explains why == on arrays compares references; use Arrays.equals to compare contents.
Two-dimensional arrays
An array can hold other arrays. A 2D array such as int[][] is an array of rows, where each row is an array of columns. Use two indexes: hall[row][seat].
import java.util.Arrays;
public class Grid {
public static void main(String[] args) {
// 3 rows of 4 seats in a small cinema: 1 = booked, 0 = free
int[][] hall = {
{1, 1, 0, 0},
{0, 1, 1, 1},
{0, 0, 0, 1}
};
System.out.println("Rows: " + hall.length + ", seats per row: " + hall[0].length);
hall[2][0] = 1; // Meera books row 3, seat 1
for (int row = 0; row < hall.length; row++) {
int free = 0;
for (int seat = 0; seat < hall[row].length; seat++) {
if (hall[row][seat] == 0) {
free++;
}
}
System.out.println("Row " + (row + 1) + ": " + free + " free");
}
System.out.println(Arrays.deepToString(hall));
int[][] triangle = new int[3][]; // jagged: rows of different lengths
for (int i = 0; i < triangle.length; i++) {
triangle[i] = new int[i + 1];
Arrays.fill(triangle[i], i + 1);
}
System.out.println(Arrays.deepToString(triangle));
}
}Rows: 3, seats per row: 4 Row 1: 2 free Row 2: 1 free Row 3: 2 free [[1, 1, 0, 0], [0, 1, 1, 1], [1, 0, 0, 1]] [[1], [2, 2], [3, 3, 3]]
hall.length is the number of rows and hall[row].length is the length of that row. Because each row is a separate array, rows can have different lengths; this is called a jagged array. Use Arrays.deepToString to print arrays of arrays.
Common mistakes
- Index out of bounds. Valid indexes are 0 to
length - 1. Loop withi < arr.length. - Writing
length()for arrays. Arrays use the fieldlength; strings use the methodlength(). - Printing an array with
println. UseArrays.toStringorArrays.deepToString. - Thinking
=copies an array. It copies the reference. Useclone()orArrays.copyOf. - Expecting an array to grow. Its size is fixed at creation. Use
ArrayListfor a changing number of items.
Key points
int[] a = {1, 2, 3};ornew int[size]creates an array; elements get default values.- Indexes start at 0, and
a.lengthgives the number of elements. java.util.ArraysprovidestoString,sort,copyOf,copyOfRange,fillandequals.- Array variables hold references:
=shares the array,clone()copies it. - 2D arrays are arrays of arrays, accessed as
grid[row][col]; rows may differ in length.
Exercise
Store the monthly electricity units of a house in Lucknow for six months: 210, 185, 240, 320, 295, 260. Write Units.java that prints the array, the total, the average with one decimal place, the month number (1 to 6) with the highest usage, and a sorted copy of the array, without changing the original order.
Show solution
import java.util.Arrays;
public class Units {
public static void main(String[] args) {
int[] units = {210, 185, 240, 320, 295, 260};
int total = 0;
int maxIndex = 0;
for (int i = 0; i < units.length; i++) {
total += units[i];
if (units[i] > units[maxIndex]) {
maxIndex = i;
}
}
int[] sorted = units.clone();
Arrays.sort(sorted);
System.out.println("Units: " + Arrays.toString(units));
System.out.println("Total: " + total);
System.out.printf("Average: %.1f%n", (double) total / units.length);
System.out.println("Highest in month " + (maxIndex + 1));
System.out.println("Sorted: " + Arrays.toString(sorted));
}
}Units: [210, 185, 240, 320, 295, 260] Total: 1510 Average: 251.7 Highest in month 4 Sorted: [185, 210, 240, 260, 295, 320]
Keeping the index of the largest value, rather than the value itself, tells you which month it was. Sorting a clone() leaves the original order untouched.
Quick Quiz
1. What is the last valid index of int[] a = new int[10];?
Indexes start at 0, so an array of 10 elements has indexes 0 to 9.
2. What does a new String[3] contain?
Arrays of reference types are filled with null by default.
3. After int[] b = a; b[0] = 5;, what is a[0]?
Assignment copies the reference, so both variables share one array.
4. How do you print the contents of an int[] named marks?
Arrays.toString formats the elements; printing the array directly shows its type and an internal code.
Learn Java with a mentor
Free lessons get you started. Our Java, C & C++ Programming training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
