Why bother with if‑else and loops?
Ever wondered how a video game knows when you win or when to spawn a new enemy? That's control flow at work – the brain of any program.
💡 In Simple Words: An if‑else tells Java to choose one path or another based on a condition, like a traffic light deciding which cars go. A loop repeats a set of instructions, just like a song that plays over and over until you hit stop.
What is an If‑else Statement?
An if‑else statement is a decision‑making tool. The word condition (the thing you test) is evaluated first. If it’s true, Java runs the code inside the if block; if it’s false, it runs the code inside the else block.
Syntax explained
if (condition) {
// code when condition is true
} else {
// code when condition is false
}
Notice the curly braces { } – they group the statements that belong together.
Real‑life analogy
Think of a school gate guard. He looks at a student’s ID (the condition). If the ID is valid, he lets the student in (the if part). If not, he asks the student to go home (the else part). Simple, right?
Loops in Java – Repeating Made Easy
Loops let you run the same code many times without copying and pasting. Java offers three main loops: while, do‑while, and for. Each one fits a different situation.
while Loop
The while loop checks the condition before each iteration. If the condition is false right away, the loop body never runs.
int i = 0;
while (i It prints numbers 0 to 4. Think of it like a water tap that only flows while you keep the faucet turned on.
do‑while Loop
A do‑while loop guarantees the body runs at least once because the condition is checked after the first execution.
int i = 0;
do {
System.out.println(i);
i++;
} while (i It behaves like a vending machine that gives you a snack first, then checks if you have enough money for another.
for Loop
The for loop bundles initialization, condition, and increment/decrement in one line – perfect when you know how many times you want to repeat.
for (int i = 0; i Imagine a row of lockers numbered 0‑4. You open each locker, peek inside, then move to the next.
Choosing the Right Loop – Quick Comparison
| Loop | Best for |
|---|---|
| while | When you don’t know how many times you’ll repeat, but you have a clear stop condition. |
| do‑while | When the code must run at least once, like menu displays. |
| for | When the number of repetitions is known beforehand. |
Putting It All Together: If‑else Inside a Loop
Often you’ll need to ask a question repeatedly – for example, keep prompting a user until they enter a correct password.
Scanner sc = new Scanner(System.in);
String correct = "java123";
String attempt;
do {
System.out.print("Enter password: ");
attempt = sc.nextLine();
if (attempt.equals(correct)) {
System.out.println("Access granted!");
} else {
System.out.println("Wrong password, try again.");
}
} while (!attempt.equals(correct));
Here the do‑while ensures the user gets at least one chance, and the if‑else decides which message to show.
Common Pitfalls to Avoid
- Forgot braces: Without
{ }, only the first line afteriforwhilebelongs to that block. - Infinite loops: If the loop condition never becomes false, the program hangs. Always update the loop variable.
- Using assignment (=) instead of comparison (==):
if (a = 5)assigns 5 toaand always evaluates true. Use==for numbers,.equals()for strings.
📝 Likely Exam Questions
- Write a Java program using a
forloop to print the first ten even numbers.for (int i = 2; i - Explain the difference between
whileanddo‑whileloops with an example.The
whilechecks the condition before the first iteration, so the body may never run. Thedo‑whileruns the body once before checking, guaranteeing at least one execution. Example shown above. - What will be the output of the following code?
int i = 0; while (i
Answer: 02 (when i is 1,continueskips the print). - Write an
if‑elsestatement that prints “Pass” if a variablemarksis 40 or above, otherwise prints “Fail”.if (marks >= 40) { System.out.println("Pass"); } else { System.out.println("Fail"); } - Describe a scenario where a
do‑whileloop is more appropriate than awhileloop.When you need to display a menu at least once and keep showing it until the user chooses to exit.