By the end of this module, you will be able to:
.length property to work with array sizefor and enhanced for loopsArrayIndexOutOfBoundsExceptionArrays utility methods (Arrays.sort, Arrays.toString)An array is a fixed-size, ordered collection of elements of the same type. Think of it as a row of numbered boxes — each box holds one value, and each box has an index starting at 0.
Index: [0] [1] [2]
Value: "Alice" "Bob" "Charlie"
You already know arrays from JavaScript. The key difference in Java is that an array can only hold one type, and its size is fixed when created — it cannot grow or shrink.
Java gives you two ways to create an array.
Use this when you know how many elements you need but don't have the values yet.
int[] scores = new int[5];
// Creates: [0, 0, 0, 0, 0]
// All slots are filled with the default value for int (0)
Use this when you already know the values upfront.
String[] cities = {"Amsterdam", "Rotterdam", "Utrecht"};
// Creates: ["Amsterdam", "Rotterdam", "Utrecht"]
// Size is automatically determined by the number of values
Both syntaxes are valid — choose whichever fits your situation.
🔍 Coming from JS, Syntax 2 looks familiar. The difference is the type (
String[]) must be declared, and all elements must be that same type.
Use square bracket notation — same as JavaScript:
String[] cities = {"Amsterdam", "Rotterdam", "Utrecht"};
System.out.println(cities[0]); // Amsterdam
System.out.println(cities[1]); // Rotterdam
System.out.println(cities[2]); // Utrecht
⚠️ Arrays in Java are zero-indexed — the first element is always at index
0, and the last is at indexlength - 1.
.length PropertyEvery Java array has a .length property that returns the number of elements.
int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers.length); // 5
🔍 In JavaScript, arrays have a
.lengthproperty too — it works the same way. One subtle difference: in Java.lengthis a field, not a method, so there are no parentheses. Compare this toString, where you call.length()with parentheses because it is a method.
String name = "Alice";
System.out.println(name.length()); // String → method, needs ()
int[] nums = {1, 2, 3};
System.out.println(nums.length); // Array → field, no ()
Assign a new value to a specific index:
String[] cities = {"Amsterdam", "Rotterdam", "Utrecht"};
cities[1] = "Delft"; // replace Rotterdam with Delft
System.out.println(cities[1]); // Delft
ArrayIndexOutOfBoundsExceptionThis is one of the most common runtime errors in Java. It happens when you try to access an index that doesn't exist in the array.
int[] numbers = {10, 20, 30}; // valid indices: 0, 1, 2
System.out.println(numbers[3]); // ❌ ArrayIndexOutOfBoundsException
System.out.println(numbers[-1]); // ❌ ArrayIndexOutOfBoundsException
Java throws this exception at runtime — the code compiles fine, but crashes when it runs.
Always make sure your index stays within 0 to length - 1:
int[] numbers = {10, 20, 30};
// ✅ Safe — the condition guarantees i never reaches numbers.length
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
💡 The most common mistake is writing
i <= numbers.lengthinstead ofi < numbers.length. The last valid index islength - 1, notlength.
for loopUse when you need the index (e.g. to modify elements or print position):
String[] fruits = {"Apple", "Banana", "Cherry"};
for (int i = 0; i < fruits.length; i++) {
System.out.println(i + ": " + fruits[i]);
}
// 0: Apple
// 1: Banana
// 2: Cherry
for loop (for-each)Use when you only need the values, not the index — cleaner and less error-prone:
String[] fruits = {"Apple", "Banana", "Cherry"};
for (String fruit : fruits) {
System.out.println(fruit);
}
// Apple
// Banana
// Cherry
💡 Prefer the enhanced
forloop when you don't need the index. It's shorter, avoids off-by-one errors, and reads naturally as "for each fruit in fruits".
The type declaration before [] determines what the array can hold. Any Java type works:
int[] scores = {95, 87, 73, 61};
double[] prices = {9.99, 14.50, 3.75};
boolean[] switches = {true, false, true, true};
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
String[] names = {"Alice", "Bob", "Charlie"};
All arrays follow the same rules regardless of type — zero-indexed, fixed size, .length property.
Java arrays are simple and fast, but they come with important constraints:
| Limitation | What it means |
|---|---|
| Fixed size | Once created, an array cannot grow or shrink. new int[5] always has exactly 5 slots. |
| Single type | All elements must be the same type. No mixing int and String. |
| No built-in methods | Arrays have no .push(), .filter(), .map() etc. like JavaScript arrays do. |
| No built-in printing | System.out.println(myArray) prints a memory address, not the contents. |
int[] nums = new int[3];
nums[3] = 99; // ❌ Can't grow — index 3 doesn't exist
💡 These limitations are why Java has the Collections framework — classes like
ArrayList,HashMap, and others that offer flexible, feature-rich alternatives. You'll cover these in the coming weeks. For now, arrays are the foundation.
Arrays Utility ClassJava's java.util.Arrays class provides helpful static methods for working with arrays. You need to import it at the top of your file.
import java.util.Arrays;
Arrays.toString() — print array contentsint[] numbers = {5, 2, 8, 1, 9};
System.out.println(numbers); // ❌ [I@1b6d3586 (memory address)
System.out.println(Arrays.toString(numbers)); // ✅ [5, 2, 8, 1, 9]
Arrays.sort() — sort an array in placeint[] numbers = {5, 2, 8, 1, 9};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers)); // [1, 2, 5, 8, 9]
String[] names = {"Charlie", "Alice", "Bob"};
Arrays.sort(names);
System.out.println(Arrays.toString(names)); // [Alice, Bob, Charlie]
💡
Arrays.sort()modifies the original array — it does not return a new sorted copy. This is different from JavaScript's.toSorted()but similar to.sort().
Create a String array of 5 of your favourite foods. Print each element using:
for loop (with the index in the output, e.g. "1. Pizza")for loop (just the food name)Given the following array, write a program that calculates and prints the sum and the average:
int[] grades = {78, 92, 65, 88, 71, 95, 83};
Expected output:
Sum: 572
Average: 81.71
Hint: use a for loop to accumulate the sum, then divide by grades.length. Watch the types — what type should hold the average?
Write a method findMax(int[] numbers) that returns the largest value in an array without using Arrays.sort().
Test it with: {34, 7, 89, 12, 56, 2}
Expected output: Max: 89