Explain it simply
Explain it simply
Picture an array as a row of numbered parking spaces. Each space holds exactly one car (one value), and the numbering starts at 0. A row of 4 spaces is numbered 0, 1, 2 and 3; there is no space number 4.
Once the row is built you cannot add spaces, and every space takes the same kind (type) of car. Arrays suit data whose size you already know, such as student marks, menu items or the days of the week.
Problem → Why → Solution
The problem: editing the copy changes the original
A teacher wants a "copy" of the marks with a 5-point bonus while leaving the original marks alone. Running the code below changes the original marks too, and printing the array shows something unreadable like [I@1b6d3586. The final loop then crashes the program with an exception.
public class Main {
public static void main(String[] args) {
int[] marks = {70, 85, 60};
int[] curved = marks; // not a copy!
for (int i = 0; i < curved.length; i++) {
curved[i] += 5;
}
System.out.println(marks[0]); // 75: the original changed
System.out.println(curved); // [I@1b6d3586 (type@hash)
for (int i = 0; i <= marks.length; i++) { // <= goes one too far
System.out.println(marks[i]);
}
}
}Why does this happen?
In Java an array is an object, and the variable only holds a reference (an address) to it. int[] curved = marks; copies the address, so both variables point to the same array. println(curved) shows the array's type code and a hash, not its contents. The last loop tries to read index 3 and throws an ArrayIndexOutOfBoundsException, because with length 3 the last index is 2.
Core concept: fixed size, zero-based, by reference
There are two ways to create an array. When you know the values, use a literal: String[] courses = {"HTML", "CSS"};. When you only know how many, use new: int[] marks = new int[3];. An array made with new is filled with default values: 0 for number types (0.0 for double), false for boolean and null for object types such as String. The size is fixed when the array is created and can never change; for a list that grows, use ArrayList from a later lesson.
Indexes start at 0, and the last index is length - 1. length is a field, not a method, so it has no parentheses: courses.length (unlike a String's length()). Reading or writing an index outside the range, such as -1 or length, throws an ArrayIndexOutOfBoundsException at runtime. Unlike C, memory is never silently corrupted, but the compiler does not catch it in advance either. Use for (int i = 0; i < arr.length; i++) when you need the index and for (int value : arr) when you only need the values.
Because an array variable is a reference, int[] b = a; creates no new array: a and b point to the same one. Passing an array to a method also passes only the reference, so changes made inside the method change the caller's array. For a real copy, use Arrays.copyOf(a, a.length) or a.clone(). a == b compares references and is false for two separate arrays with the same contents; compare contents with Arrays.equals(a, b). To print one, you need Arrays.toString().
int[] alias = marks; vs int[] copy = Arrays.copyOf(marks, 3);
---------------------------------------------------------------
marks --+
+--> [ 70 | 85 | 99 ] one array, two names
alias --+ 0 1 2
copy -----> [ 70 | 85 | 0 ] a separate array
0 1 2- new builds a row of slots in memory
- The variable holds that row's address
- = copies only the address
- Arrays.copyOf() builds a new row
When two variables hold the same address, a change made through one is visible through the other.
General pattern
Type[] name = {value0, value1, value2}; // size from the values
Type[] empty = new Type[size]; // filled with 0 / false / null
Type first = name[0];
name[name.length - 1] = newValue; // last valid index
for (int i = 0; i < name.length; i++) { /* name[i] */ }
for (Type item : name) { /* read each item */ }
Type[] copy = Arrays.copyOf(name, name.length); // import java.util.ArraysAdding [] after a type makes an array type. Read and write with [index], and name.length is the number of elements. Use Arrays.copyOf() when you need a copy, never plain =.
Example: a course list and a marks array
The first half reads a String array, changes one element and loops over it with an index. The second half shows the default values of new int[3], Arrays.toString(), and the difference between an alias and a copy. Predict the "marks" and "copy" lines before you run it.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] courses = {"HTML", "CSS", "Java", "Python"};
System.out.println(courses[0]);
courses[2] = "Advanced Java";
System.out.println("Total courses: " + courses.length);
for (int i = 0; i < courses.length; i++) {
System.out.println((i + 1) + ". " + courses[i]);
}
int[] marks = new int[3];
marks[0] = 70;
marks[1] = 85;
System.out.println(Arrays.toString(marks));
int[] alias = marks;
int[] copy = Arrays.copyOf(marks, marks.length);
alias[2] = 99;
System.out.println("marks: " + Arrays.toString(marks));
System.out.println("copy: " + Arrays.toString(copy));
}
}Code breakdown
- Line 5
String[] courses = {"HTML", "CSS", "Java", "Python"};The array literal creates an array of length 4 from four values. Its indexes run from 0 to 3.
- Line 8
courses[2] = "Advanced Java";Index 2, the third element, is replaced with a new value. Elements can change, but the size of the array cannot.
- Line 11
for (int i = 0; i < courses.length; i++) {Starting at 0 with < length visits exactly indexes 0 to 3. The print uses (i + 1) because people expect numbering to start at 1.
- Lines 15-18
System.out.println(Arrays.toString(marks));new int[3] starts as [0, 0, 0], and only indexes 0 and 1 are filled, so [70, 85, 0] is printed. Without Arrays.toString() you would see [I@... instead.
- Lines 20-22
alias[2] = 99;alias points to the same array as marks, so after alias[2] = 99, marks is [70, 85, 99]. copy was built as a separate array before that change, so it stays [70, 85, 0].
HTML
Total courses: 4
1. HTML
2. CSS
3. Advanced Java
4. Python
[70, 85, 0]
marks: [70, 85, 99]
copy: [70, 85, 0]2D arrays, sorting and equality
In Java a 2D array is an array of arrays. grid.length is the number of rows, grid[0].length is the number of columns in the first row, and grid[1][2] is row 1, column 2. Rows may even have different lengths (a jagged array). Arrays.sort() sorts an array in place, and Arrays.deepToString() prints nested arrays.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[][] grid = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(grid.length + " rows, " + grid[0].length + " columns");
System.out.println("grid[1][2] = " + grid[1][2]);
System.out.println(Arrays.deepToString(grid));
int[] a = {3, 1, 2};
int[] b = {1, 2, 3};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
System.out.println("a == b: " + (a == b));
System.out.println("Arrays.equals: " + Arrays.equals(a, b));
int total = 0;
for (int value : b) {
total += value;
}
System.out.println("Sum with enhanced for: " + total);
}
}After sorting, a holds the same contents as b, yet a == b is false because they are two separate objects. Arrays.equals(a, b) compares element by element and gives true.
In real projects
Where this shows up in real projects
Application code usually prefers ArrayList for data whose size changes, such as cart items or user lists, but arrays are everywhere. The args in main(String[] args) is the array of command-line arguments. "a,b,c".split(",") returns a String[], and bytes read from a file arrive as a byte[]. Image pixels, game boards and matrix calculations use 2D arrays, and in performance-sensitive code an int[] uses far less memory than a list of Integer objects.
Bugs caused by reference semantics come up in code reviews all the time. When a class returns its private array straight from a getter, a caller who modifies that array also changes the object's internal state. Well-designed APIs therefore return a defensive copy made with Arrays.copyOf(), or an unmodifiable List.of(...), a topic the encapsulation lesson returns to.
Common mistakes
Common mistakes
1. Using length as the last index
With four courses, courses[4] or courses[courses.length] throws an ArrayIndexOutOfBoundsException, because the valid indexes are only 0, 1, 2 and 3. Write courses[courses.length - 1] for the last element and use i < length in loops.
2. Treating = as a copy
After int[] backup = scores;, sorting scores sorts backup too: there is no backup at all. Create a new array with Arrays.copyOf(), clone() or System.arraycopy(). Remember that for object arrays such as String[] the copy is shallow: the element objects themselves are not duplicated.
3. Using println and == directly on arrays
System.out.println(marks) shows a type and hash such as [I@1b6d3586, not the contents; use Arrays.toString(marks). Likewise, if (a == b) is false for equal contents in different objects; use Arrays.equals(a, b).
Best practices
Best practices
- Prefer the enhanced for when you do not need the index; with no index there is no off-by-one.
- Use ArrayList for data whose size changes instead of resizing arrays by hand.
- Make it clear in the method name and comments whether a method that takes an array modifies it or only reads it.
- When an array is stored in a field, copy both the incoming array and any array you hand back.
Mini challenge
Mini challenge: mark statistics
Write methods that take an int[] of marks and return the average, the highest mark, the number of passes and a new array with a bonus added. The original array must not change.
- average(marks): returns a double, 0.0 for an empty array
- highest(marks): the highest mark (assume the array is not empty)
- countPasses(marks, passMark): how many marks are passMark or above
- withBonus(marks, bonus): returns a new array, capped at 100, without touching the original
- Use {72, 38, 95, 61, 40} with a bonus of 8 and print arrays with Arrays.toString()
import java.util.Arrays;
public class Main {
static double average(int[] marks) {
// TODO: guard the empty array, sum with a loop, avoid int division
return 0.0;
}
static int highest(int[] marks) {
// TODO: start from marks[0] and compare the rest
return 0;
}
static int countPasses(int[] marks, int passMark) {
// TODO: count marks >= passMark
return 0;
}
static int[] withBonus(int[] marks, int bonus) {
// TODO: copy first, then add the bonus (max 100)
return marks;
}
public static void main(String[] args) {
int[] marks = {72, 38, 95, 61, 40};
// TODO: print average, highest, passes, curved and original arrays
}
}Expected: The program prints these six lines (the Original line must be unchanged): Average: 61.2 Highest: 95 Passed: 4 of 5 Curved: [80, 46, 100, 69, 48] Original: [72, 38, 95, 61, 40] Empty average: 0.0
Show hint
For the average, cast before dividing: (double) sum / marks.length. In withBonus, copy first with Arrays.copyOf(marks, marks.length), then use Math.min(100, value + bonus).
Show solution
import java.util.Arrays;
public class Main {
static double average(int[] marks) {
if (marks.length == 0) {
return 0.0;
}
int sum = 0;
for (int mark : marks) {
sum += mark;
}
return (double) sum / marks.length;
}
static int highest(int[] marks) {
int best = marks[0];
for (int i = 1; i < marks.length; i++) {
if (marks[i] > best) {
best = marks[i];
}
}
return best;
}
static int countPasses(int[] marks, int passMark) {
int count = 0;
for (int mark : marks) {
if (mark >= passMark) {
count++;
}
}
return count;
}
static int[] withBonus(int[] marks, int bonus) {
int[] result = Arrays.copyOf(marks, marks.length);
for (int i = 0; i < result.length; i++) {
result[i] = Math.min(100, result[i] + bonus);
}
return result;
}
public static void main(String[] args) {
int[] marks = {72, 38, 95, 61, 40};
System.out.println("Average: " + average(marks));
System.out.println("Highest: " + highest(marks));
System.out.println("Passed: " + countPasses(marks, 40) + " of " + marks.length);
System.out.println("Curved: " + Arrays.toString(withBonus(marks, 8)));
System.out.println("Original: " + Arrays.toString(marks));
System.out.println("Empty average: " + average(new int[0]));
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- An array stores values of one type with a fixed size; arrays made with new start as 0, false or null.
- Indexes run from 0 to length - 1; length is a field without parentheses, and out-of-range access throws an ArrayIndexOutOfBoundsException.
- An array variable is a reference: = is not a copy, so use Arrays.copyOf() or clone().
- Print with Arrays.toString(), compare with Arrays.equals() and sort with Arrays.sort().