Java OOP · Module 0
Decisions and repetition
if / else, comparison, and the three loops you need
What you'll be able to do
- Write an if / else if / else chain that reads like a sentence
- Use ==, !=, >, <, && and || correctly
- Choose between for, while and for-each
- Know why comparing text with == is a trap
if / else
Making decisions with if / else
Validation — the heart of Module 4 — is nothing more than an if statement placed in the right spot.
An if runs a block only when a boolean condition is true. Add else if for alternatives and else for everything that is left. Java checks the branches top to bottom and stops at the first true one.
Operators you will use constantly
| Operator | Means | Example |
|---|---|---|
| == | equal to (same value / same object) | amount == 0 |
| != | not equal to | status != 1 |
| >= <= | greater / less or equal | amount <= balance |
| && | and — both must be true | amount > 0 && amount <= balance |
| || | or — at least one is true | isAdmin || isOwner |
| ! | not — flips a boolean | !isClosed |
== on text compares boxes, not contents
For String (and every object) == asks *are these the same object in memory?* while .equals(...) asks *do they contain the same characters?* Use name.equals("Sara"). You will meet this rule again the moment you create your first objects.
Change `score` to 95, then to 40, and predict each output before running.
Loops
Repeating work: for, while, for-each
The classic counting loop
;: start (int i = 1), keep-going test (i <= 3), and step (i++, meaning add one).<= to < and it runs twice — that is the famous off-by-one bug.Which loop should I use?
for / for-each
You know how many times
- for-each reads as 'for each grade in grades'
- No index to get wrong — fewer bugs
- Use a classic for when you actually need the index
while
You repeat until something changes
- The condition is checked before every round
- Forget to change the variable and it loops forever
- Perfect when the number of rounds is unknown
Common mistakes
if (score = 90) { ... }if (name == "Sara") { ... }while (countdown > 0) { System.out.println(countdown); }Lesson playground
Print a times table. Change the multiplier or the loop bounds and watch what happens.
Check understanding
Quiz
Question 1 of 4
Predict the complete output.
Summary
- `if / else if / else` picks the first true branch, so order the conditions from strictest to loosest.
- Combine conditions with `&&` (both) and `||` (either) — mixing them up breaks validation silently.
- Use `.equals(...)` for text, never `==`.
- for = known count, for-each = walk a collection, while = repeat until something changes.