Week 1

Environment setup

How Java works

Types and Variables

Arrays

Basic IO

Control Flow

Packages

OOP in Java

Static Members

Practice

Assignment

Back end Track

🎯 Learning Objectives

By the end of this module, you will be able to:


1. What is an Array?

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.


2. Declaring and Initialising Arrays

Java gives you two ways to create an array.

Syntax 1 — Declare size, fill later

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)

Syntax 2 — Declare with values (array literal)

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.


3. Accessing Elements by Index

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 index length - 1.


4. The .length Property

Every 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 .length property too — it works the same way. One subtle difference: in Java .length is a field, not a method, so there are no parentheses. Compare this to String, 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 ()

5. Modifying Elements

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

6. ArrayIndexOutOfBoundsException

This 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.

How to avoid it

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.length instead of i < numbers.length. The last valid index is length - 1, not length.


7. Iterating Arrays

Standard for loop

Use 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

Enhanced 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 for loop when you don't need the index. It's shorter, avoids off-by-one errors, and reads naturally as "for each fruit in fruits".


8. Arrays of Different Types

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.


9. Limitations of Arrays

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.


10. The Arrays Utility Class

Java'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 contents

int[] 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 place

int[] 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().


✏️ Exercises

Exercise 1 — Declare & Access

Create a String array of 5 of your favourite foods. Print each element using:


Exercise 2 — Sum & Average

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?


Exercise 3 — Find the Maximum

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


Exercise 4 — Spot the Bug