MA-JAVA0 · Module 3
Branching, user input, and loops
Topics: if/else · User input · for · while
Overview
Session 3 — Branching, user input, and loops
You will steer execution with if / else, read user input (with Scanner on System.in), and practise for / while loops — including counting up and down, filtering with %, and building a string by concatenation.
These skills match a typical Week 2–3 intro syllabus (booleans/branching/input → collections & loops).
Time: about 90 minutes with tracing exercises.
Concepts
1. Why methods exist
A method names a chunk of work, lists parameters (inputs), and optionally returns a value to its caller. Benefits:
- Reuse — write once, call from many places.
- Testing — you can reason about small pieces in isolation.
- Readability —
double tip = gratuity(subtotal, 0.18);reads like intent.
Method syntax inside a class:
static double clamp(double value, double min, double max) {
if (value < min) {
return min;
}
if (value > max) {
return max;
}
return value;
}
static here means “callable without constructing an object”—perfect while every program lives inside main in early sessions.
2. Parameters are copies (for primitives)
When you pass an int into a method, Java copies its bits into the parameter slot. Mutations inside the method do not rename variables in the caller:
static void bump(int x) {
x = x + 1;
}
Calling bump(count) never changes count in main. Reference parameters behave differently—Session 6. For a runnable trace, see Example C on the Examples tab.
3. if, else if, else
Conditions must be boolean expressions—Java refuses if (count) like C does.
if (tempC <= 0) {
System.out.println("freeze watch");
} else if (tempC >= 35) {
System.out.println("heat watch");
} else {
System.out.println("comfort band");
}
Brace rule: always brace multi-line bodies—even when the compiler allows a single statement without braces—so future edits do not create dangling lines.
4. switch (classic style first)
switch (dayCode) {
case 1:
System.out.println("Mon");
break;
case 2:
System.out.println("Tue");
break;
default:
System.out.println("other");
}
Forgetting break falls through to the next case—occasionally intentional, usually a bug. Modern Java offers switch expressions; learn classic switch first so historical code reads fluently.
5. User input
import java.util.Scanner;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer:");
int n = in.nextInt();
6. Loops
for shines when you know iteration count or an index range:
for (int i = 0; i < 5; i++) {
System.out.println("tick " + i);
}
// Inclusive upper bound
for (int i = 45; i <= 59; i++) {
System.out.println(i);
}
// Count down
for (int i = 17; i >= 0; i--) {
System.out.println(i);
}
while checks condition before each iteration — good for “repeat until” and string accumulation:
int n = 0;
while (n < 3) {
n++;
}
String hey = "";
int count = 0;
while (count < 5) {
hey += "Hey! ";
count++;
}
do { ... } while (condition); runs at least once—handy for menu loops reading user input.
7. break and continue
breakexits the innermost loop orswitch.continueskips to the next iteration of the innermost loop.
Labelled breaks exist for nested structures—ignore until you need them.
8. Style tips
- Prefer guard clauses (
if (invalid) return;) to reduce nesting. - Name methods with verbs (
computeTotal,normalise). - Keep
mainthin—delegate to static helpers as files grow.
9. Method overloading (same name, different parameters)
Java lets several methods share a name if their parameter lists differ (count or types). The compiler picks the best match at each call site—return type alone is not enough to distinguish overloads.
public static int add(int a, int b) {
return a + b;
}
public static double add(double a, double b) {
return a + b;
}
Overloading is resolved at compile time. It is not the same as overriding in subclasses (session 13), which depends on the runtime type of the object.
Examples
Example A — guard clauses
public class Rsvp {
public static String seatLabel(int n) {
if (n <= 0) {
return "invalid";
}
if (n > 200) {
return "overflow";
}
return "table-" + n;
}
public static void main(String[] args) {
System.out.println(seatLabel(12));
System.out.println(seatLabel(-3));
}
}
Each failure mode returns early; the “happy path” stays flat.
Example B — user input with Scanner
import java.util.Scanner;
public class AskAge {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer:");
int n = in.nextInt();
System.out.println("You typed " + n);
}
}
Read the prompt, then store the value in a named variable before the loop that uses it.
Example C — for-loop ranges (tutorial-style)
public class RangeDrills {
public static void main(String[] args) {
// Print 45..59 inclusive (each on its own line)
for (int i = 45; i <= 59; i++) {
System.out.println(i);
}
// Count down 17..0 inclusive
for (int i = 17; i >= 0; i--) {
System.out.println(i);
}
// Odds only in 45..59
for (int i = 45; i <= 59; i++) {
if (i % 2 != 0) {
System.out.println(i);
}
}
// Multiples of 3 from 17 down to 0
for (int i = 17; i >= 0; i--) {
if (i % 3 == 0) {
System.out.println(i);
}
}
}
}
Inclusive bounds use <= / >=. Filters use % inside the loop body.
Example D — while loop string accumulation
public class HeyLoop {
public static void main(String[] args) {
String hey = "";
int count = 0;
while (count < 5) {
hey += "Hey! ";
count++;
}
System.out.println(hey); // "Hey! Hey! Hey! Hey! Hey! "
// Change the guard to count < 20 for twenty copies
}
}
Initialise the accumulator before the loop; update the counter inside or the loop never ends.
Example E — countdown with even / odd
import java.util.Scanner;
public class CountdownParity {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer:");
int n = in.nextInt();
while (n >= 1) {
if (n % 2 == 0) {
System.out.println(n + " is EVEN");
} else {
System.out.println(n + " is ODD");
}
n--;
}
}
}
Same skeleton as a classic tutorial Countdown task: loop down to 1, report parity each step.
Example F — parameters are copies (primitives only)
Java always passes arguments by value. For primitives, assigning to the parameter only rewrites the copy.
public class TickCounter {
static void pretendAddOne(int ticks) {
ticks = ticks + 1;
System.out.println("inside pretendAddOne, ticks == " + ticks);
}
public static void main(String[] args) {
int count = 40;
System.out.println("before call: count == " + count);
pretendAddOne(count);
System.out.println("after call: count == " + count); // still 40
}
}
If the caller needs an updated primitive, return the new value (or later share a mutable object — Session 6).
Example G — compound interest (for and while)
$10{,}000$ at 5% per month for 2 years (24 months). Each month multiply the balance by 1.05.
for version:
public class SavingsFor {
public static void main(String[] args) {
double savings = 10_000.0;
for (int month = 1; month <= 24; month++) {
savings = savings * 1.05;
}
System.out.println("After 24 months: " + savings);
}
}
while version (same maths):
public class SavingsWhile {
public static void main(String[] args) {
double savings = 10_000.0;
int month = 1;
while (month <= 24) {
savings = savings * 1.05;
month++;
}
System.out.println("After 24 months: " + savings);
}
}
After the 5th iteration (5 months), savings ≈ 12762.82 (exact: 10000 × 1.05^5 = 12762.815625). Trace on paper: start 10000, multiply by 1.05 five times.
Bridge
Control flow ↔ upcoming object lessons
-
Static helpers mirror the
Math.maxstyle in the JDK—later you will replacestaticutilities with instance methods when data varies per object. -
Loops over arrays (Session 4) reuse identical syntax—only the termination condition changes.
-
Switch fall-through stories prepare you for parser-style code in compilers courses—rare in app code, common in textbooks.
-
Guard clauses become validation inside constructors once you wrap state in classes.
When main is mostly method calls, you are ready for structured data.
Practice check — branching, user input, and loops
Multiple-choice check from the Matheion app lesson. Pick an answer for each question, then submit.
1.After this loop, what is printed? ```java int i = 0; while (i < 3) { i++; if (i == 2) continue; System.out.print(i); } ```
2.Which loop prints integers from 45 through 59 inclusive?
3.You want `hey` to become `"Hey! Hey! Hey! "` using concatenation. Which approach is correct?
4.In a countdown that prints whether `n` is even or odd, which test is correct?
5.Why is forgetting `break` in a classic `switch` often dangerous?