1. Why arrays?
Store the marks of 50 students with separate variables? marks1, marks2, ... marks50 would be impossible to loop over. An array is a single variable holding a fixed number of values of the same type, stored side by side and accessed by position.
Real-life analogy: A row of lockers
A row of numbered lockers at a railway station: all the same size, numbered from 0, and you open one by its number. The whole row has one name, like marks.
2. Creating arrays
public class Main { public static void main(String[] args) { // Way 1: you know the values int[] marks = {78, 92, 65, 88, 70}; // Way 2: you know only the size double[] prices = new double[3]; // three slots, all 0.0 at first prices[0] = 49.5; prices[1] = 120.0; prices[2] = 15.75; System.out.println(marks[0]); // 78 (first element) System.out.println(marks[4]); // 70 (last element) System.out.println(marks.length); // 5 marks[2] = 67; // update the third element }}-
Indexes start at 0. The last index is always
length - 1. -
new double[3]creates space for 3 values. The wordnewmeans "create a fresh block of memory". We'll meetnewagain, in a much bigger role, in Session 14. -
lengthhas no brackets for arrays (it's a property, not a method). -
Arrays have a fixed size; once created, they can't grow.
Note: Back to the frame
Look at main again: public static void main(String[] args). Now you can read String[] args: a parameter named args whose type is an array of Strings. Java fills it with any text values typed after the program name when it starts. We'll use it later
Default values when you create with new: 0 for numbers, 0.0 for decimals, false for boolean, '\u0000' (an invisible "nothing" character) for char, and null for Strings.
3. Looping over arrays
int[] marks = {78, 92, 65, 88, 70};// Classic for: when you need the indexfor (int i = 0; i < marks.length; i++) { System.out.println("Student " + (i + 1) + ": " + marks[i]);}// for-each: when you only need the valuesint total = 0;for (int m : marks) { total += m;}System.out.println("Average: " + (double) total / marks.length);Read for (int m : marks) as "for each int m in marks". It's simpler and safer, but it can't tell you the index and can't change the array's elements.
4. Going past the end
int[] a = {10, 20, 30};System.out.println(a[3]);Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 at Demo.main(Demo.java:3)The valid indexes are 0, 1 and 2. Read the message the way we learned in Session 6: first line for what, your file name for where.
Promise: we will open this box properly later
Notice the words in thread "main" in every crash message. For now, "your program runs on something called a thread, and the main thread is the one that runs
main." In Session 35 we'll create our own threads and run several things at the same time.
5. Arrays in memory: stack and heap
This is one of the most important ideas in the whole course, so take it slowly.
Java's memory has two main areas:
-
Stack: holds method frames with their local variables (Session 9). Small and fast.
-
Heap: a large area where bigger things, like arrays (and, later, objects), are created.
A primitive variable (int x = 5) holds its value directly on the stack. An array variable does not hold the array; it holds a reference (like an address) pointing to the array, which lives on the heap.
Why this matters: copying
Remember Session 3, problem 4? With int b = a;, changing a later didn't affect b. Arrays behave differently:
public class Main { public static void main(String[] args) { int[] a = {1, 2, 3}; int[] b = a; // copies the REFERENCE, not the array b[0] = 99; System.out.println(a[0]); // 99! a and b point to the same array }}Visualise it: paste this code into the Java Visualizer at this link (inside the wrapper from the "How to use" section) and step through. The arrow from b to the same array makes it obvious.
Arrays and methods
import java.util.Arrays;public class Main { public static void main(String[] args) { int[] nums = {1, 2, 3}; doubleAll(nums); System.out.println(Arrays.toString(nums)); // [2, 4, 6] } static void doubleAll(int[] arr) { for (int i = 0; i < arr.length; i++) { arr[i] *= 2; } }}In Java Methods Explained: A Complete Beginner’s Guide, a method couldn't change the caller's int. Here it did change the caller's array. Java is still pass-by-value: it copied the reference, and both references point to the same array on the heap.
6. The Arrays toolbox
int[] a = {5, 2, 9, 1};System.out.println(Arrays.toString(a)); // [5, 2, 9, 1]Arrays.sort(a); // a is now [1, 2, 5, 9]int[] copy = Arrays.copyOf(a, a.length);Arrays.fill(copy, 7); // [7, 7, 7, 7]System.out.println(Arrays.equals(a, copy)); // falseLike Scanner, Arrays lives in java.util, so the file needs import java.util.Arrays; at the top (promise P9 again).
System.out.println(a) alone prints something like [I@6d06d69c, not the values. Always use Arrays.toString(a).
7. 2D arrays
A 2D array is an array of arrays, like a table with rows and columns:
public class Main { public static void main(String[] args) { int[][] matrix = { {1, 2, 3}, {4, 5, 6} }; System.out.println(matrix[1][2]); // row 1, column 2 → 6 System.out.println(matrix.length); // 2 rows System.out.println(matrix[0].length); // 3 columns for (int r = 0; r < matrix.length; r++) { for (int c = 0; c < matrix[r].length; c++) { System.out.print(matrix[r][c] + "\t"); } System.out.println(); } }}
Because each row is its own array, rows can have different lengths (a jagged array): int[][] j = new int[3][]; then j[0] = new int[2]; and so on.
Common mistakes
-
Using index
lengthinstead oflength - 1for the last element. -
Writing
arr.length()(that's for Strings) instead ofarr.length. -
Printing an array directly and getting
[I@6d06d69c. -
Thinking
b = acopies an array. -
Trying to change elements in a for-each loop:
for (int x : arr) x = 0;changes only the copyx.
Interview Questions
What are the default values of array elements?
0 for integer types, 0.0 for floating types, false for boolean, '\u0000' for char, and null for references such as String.
What is the difference between arr.length and str.length()?
length is a field of arrays; length() is a method of String.
If you pass an array to a method and the method modifies it, does the caller see the change? Why?
Yes. Java passes a copy of the reference, and both references point to the same array object on the heap. However, if the method assigns a new array to its parameter, the caller's variable is unaffected.
Where are arrays stored in memory?
Arrays are objects, so they're allocated on the heap. The array variable holds a reference to them.
Practice
-
easy Read 5 numbers into an array and print their sum, average, maximum and minimum.
-
easy Linear search: return the index of a value in an array, or -1 if not found.
-
easy Count how many even and odd numbers an array contains.
-
medium Reverse an array in place (without creating a second array).
-
medium Find the second-largest element in one pass.
-
medium Move all zeros to the end while keeping the order of other elements:
[0, 1, 0, 3, 12]→[1, 3, 12, 0, 0].



Discussion