Day 17 / 25 Java Control Flow, Arrays & Methods 0/0 exercises Exercises ↓

AmouAI Hub/Courses/Programming Fundamentals/Day 17

Week 4 · Java: A Second Lens · Day 17

Java Control Flow, Arrays & Methods

Familiar structures, unfamiliar rules — including the == versus .equals() trap that catches every single beginner exactly once.

Study time
4 hours
Reading
Head First Java, Ch. 3–4
Focus
arrays · overloading · == vs .equals

By the end of today you can

  1. Write if, while, classic for and enhanced for in Java
  2. Use switch, including the modern arrow form
  3. Declare, fill and iterate a fixed-size array
  4. Predict ArrayIndexOutOfBoundsException before it happens
  5. Say exactly what == compares, and when to use .equals()
  6. Overload a method, and say why Python cannot
  7. Explain Java's pass-by-value — including for objects

Today's videos

Watch each video, then work the matching sections below. Watching alone will not do it.

17A
Control Flow & Arrays (120 min)
if/else if, the classic for and the enhanced for · why you always use braces · the arrow switch · fixed-size arrays · .length versus .size() · no negative indexing, no slicing.
17B
== versus .equals(), and Pass-by-Value (120 min)
The string pool and why == appears to work · the bug that only shows up with real data · Objects.equals · method overloading, and why Python cannot · pass-by-value for primitives and for references.

1Control flow

Same shapes, more punctuation.

The dangling-else bug that Python cannot have

Java allows a single statement without braces: if (x) doThing();. Add a second line later and only the first is conditional — with indentation that lies about it. Always use braces, even for one line. Python's indentation makes this bug impossible; Java's does not.

switch

Switch.java
// modern arrow form — no fall-through, no break needed
String kind = switch (day) {
    case "SAT", "SUN" -> "weekend";
    case "MON", "TUE", "WED", "THU", "FRI" -> "weekday";
    default -> "unknown";
};

The old switch used case X: with an explicit break, and forgetting the break meant execution fell through into the next case — a famous source of bugs. The arrow form removes the hazard. Python only got a comparable construct in 3.10 (match), and you will rarely need it.

2Arrays

Fixed size, one type, decided at creation.

Arrays.java
int[] scores = new int[5];        // five ints, all 0
scores[0] = 23;
scores[1] = 45;

int[] ready = {23, 45, 12, 67};   // declared and filled

System.out.println(ready.length); // a field, not a method — no ()
System.out.println(ready[3]);

for (int score : ready) {
    System.out.println(score);
}

System.out.println(ready[4]);     // ArrayIndexOutOfBoundsException
Python listJava array
SizeGrows on demandFixed at creation
TypesAnything, mixedOne type, declared
Lengthlen(xs)xs.length — a field, no brackets
Add an itemxs.append(x)Not possible — build a bigger array, or use ArrayList
Out of rangeIndexErrorArrayIndexOutOfBoundsException
Negative indexCounts from the endAlso out of bounds — no wrapping
Two habits to unlearn today

xs[-1] does not mean "last" in Java — it throws. Write xs[xs.length - 1]. And there is no slicing: Arrays.copyOfRange(xs, 1, 4) is the closest equivalent, and it follows the same include-start, exclude-stop rule you learned on Day 8.

The fixed size is genuinely limiting, and Java knows it — ArrayList on Day 20 is the growable version, and it is what you will actually use. Arrays are worth meeting first because they are what ArrayList is built from.

3== versus .equals()

The trap in the day's subtitle. It catches everyone exactly once.

Why this one is so dangerous

It usually works. Literals are pooled, so == on strings appears correct all through your learning — and then fails on a string that came from a file, a database or user input, because those are not literals. A bug that only appears with real data is the worst kind.

ComparisonAsksUse for
a == bSame object? (same address)Primitives, and deliberate identity checks
a.equals(b)Same contents?Objects — this is almost always what you want
Objects.equals(a, b)Same contents, null-safeWhen either side might be null
Which is why this day exists

This is the clearest example of the course's whole argument for a second language. You knew is and == were different in Python, abstractly. Java makes you feel it, because getting it wrong here produces a bug rather than a shrug.

4Overloading and pass-by-value

Two things Java does that Python simply cannot.

Overload.java
static int add(int a, int b) {
    return a + b;
}

static double add(double a, double b) {   // same name
    return a + b;
}

static String add(String a, String b) {   // same name again
    return a + b;
}

// the compiler picks by the argument types
add(1, 2);          // -> the int version
add(1.5, 2.5);      // -> the double version
add("a", "b");      // -> the String version
Python cannot do this, and does not need to

Define add twice in Python and the second definition simply replaces the first — there is one name and one function. Python solves the same problem with default arguments and duck typing: one add that accepts anything supporting +. Java solves it by having three methods and letting the compiler choose. Static types make overloading possible; dynamic types make it unnecessary.

Pass-by-value, precisely

Java always passes a copy of the value. For a primitive, that is a copy of the number. For an object, it is a copy of the reference — so both names point at the same object.

This is Day 8's aliasing lesson, in Java

"You can change the object, but you cannot change which object the caller is looking at." That is true in Python too — xs.append(1) inside a function is visible to the caller; xs = [1] is not. Java's explicit types just make the distinction impossible to ignore.

>_Python playground

A real Python interpreter running inside your browser. Nothing is installed, nothing is uploaded, nothing can break.

scratch.pypython not loaded
Values for input(), comma separated →
Output appears here. The first run takes a few seconds while Python loads.

Exercise set

Checked automatically the moment you submit. Work top to bottom — each one assumes the last. Your answers are saved in this browser.

All Warm-up Core Challenge Reset day

Day 18 — Java Classes, Objects & Encapsulation

Constructors, access modifiers, and why Java needs getters.

Continue →