Module 2 — Control Flow and Logic
This module teaches how programs make decisions and repeat tasks using conditions and loops. You’ll learn to guide the flow of execution to build interactive, intelligent Java programs.
2.1 — Overview
Every program must make choices: what to do next depends on conditions. Java provides:
- Conditional statements — decide which code to run (
if,switch). - Loops — repeat code while a condition is true (
for,while,do-while). - Control keywords — alter normal flow (
break,continue,return).
2.2 — Conditional Statements
if statement
int age = 20;
if (age >= 18) {
System.out.println("Adult");
}
if-else statement
if (age >= 18) {
System.out.println("Adult");
} else {
System.out.println("Minor");
}
if-else if ladder
int score = 85;
if (score >= 90) {
System.out.println("A");
} else if (score >= 75) {
System.out.println("B");
} else if (score >= 60) {
System.out.println("C");
} else {
System.out.println("Fail");
}
switch statement
Use switch for multiple discrete values.
int day = 3;
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
default: System.out.println("Other day");
}
2.3 — Loops
Loops allow repetition of code while a condition remains true.
for loop
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
while loop
int i = 1;
while (i <= 5) {
System.out.println("Count: " + i);
i++;
}
do-while loop
The body runs at least once even if the condition is false.
int n = 1;
do {
System.out.println("Number: " + n);
n++;
} while (n <= 3);
2.4 — Nested Loops and Flow Control
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
System.out.print("* ");
}
System.out.println();
}
Control keywords:
break— exit the nearest loop or switch.continue— skip the current iteration and continue the next one.
for (int i = 1; i <= 5; i++) {
if (i == 3) continue; // skip 3
if (i == 5) break; // stop loop
System.out.println(i);
}
2.5 — Logical and Relational Operators
Used in conditions to test values.
- Relational:
>,<,>=,<=,==,!= - Logical:
&&(AND),||(OR),!(NOT)
int x = 5, y = 10;
if (x < y && y < 20) {
System.out.println("Condition true");
}
2.6 — Mini Projects / Practice
Ask for an integer and print whether it’s odd or even.
Read two numbers and an operator (+ − * /). Use switch to perform the correct calculation.
Input N and use a loop to compute 1 + 2 + … + N.
Print a 1–10 multiplication table using nested loops.
Generate a random number (1–100). Ask the user to guess until correct,
using hints like “Too high” or “Too low”.
Use while(true) and break to exit when guessed.
2.7 — Summary
ifandswitchcontrol decision making.for,while,do-whilehandle repetition.breakandcontinuemodify loop execution.- Combine conditions with logical operators for complex logic.
Next Module → Functions and Methods: learn to organize reusable blocks of code.