Skip to content
QuizMaker logoQuizMaker
Activity
Java Programming: From Zero to Enterprise
1. Java Fundamentals
1. Getting Started with Java & the JVM
2. Data Types & Variables
3. Control Flow: Ifs & Loops
4. String Manipulation in Depth
5. Methods (Functions) Architecture
6. Arrays & The Enhanced For Loop
7. User Input via Scanner
8. Mathematical Operations & The Math Class
9. Operators in Depth
10. Block Scope & Variable Lifecycles
11. Introduction to Object-Oriented Programming
12. Classes & Instances Deep Dive
13. Constructors
14. Encapsulation & The 'this' Keyword
15. Inheritance: Extending Functionality
16. Polymorphism & Method Overriding
17. Abstraction & Abstract Classes
18. Interfaces: The Ultimate Contract
19. Packages & Access Modifiers
20. Enums (Enumerations)
21. Exceptions: Handling Runtime Errors
22. The 'throw' and 'throws' keywords
23. Dates, Times, and Formatting
24. Enumerable Data Structures
25. LinkedLists: The Alternative
26. HashMaps: Key-Value Architecture
27. HashSets: The Art of Uniqueness
28. Iterator: Safe Collection Traversal
29. Wrapper Classes & Autoboxing
30. Basic File I/O
31. Generics: Type-Safe Templates
32. Lambda Expressions & Functional Interfaces
33. The Stream API: Functional Data Pipelines
34. Optional: Beating the NullPointerException
35. Multithreading & Concurrency Basics
36. JDBC: Connecting to SQL Databases
37. Annotations & Reflection
38. The JVM Garbage Collector
39. Introduction to Spring Boot
40. Unit Testing with JUnit
41. Java Collections for DSA
CONTENTS

3. Control Flow: Ifs & Loops

Direct the execution of your code dynamically.

Java Programming: From Zero to Enterprise
1. Java Fundamentals
February 22, 2026
113
A

[!NOTE] Programs rarely execute straight from top to bottom. You need decision-making logic and repeat logic to build anything useful. Welcome to Control Flow.

IF-Else Statements

The most basic form of decision making. You evaluate a boolean expression, and execute a block of code if it is true.

int speed = 80;

if (speed > 70) {
    System.out.println("You are speeding! Ticket issued.");
} else if (speed > 40) {
    System.out.println("Good pace. Safe driving.");
} else {
    System.out.println("You are driving too slow.");
}

The Switch Statement

If you have many else if conditions checking the same variable against specific, strict values, use a switch block to dramatically improve readability and performance.

int dayOfWeek = 3;

switch(dayOfWeek) {
    case 1:
        System.out.println("Monday");
        break; // Crucial! Prevents "falling through" to the next case.
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    default:
        System.out.println("Weekend!");
}

Loops: Automating Repetition

When you need to execute the same logic multiple times, use a loop. Java provides several types depending on your needs.

  1. The For Loop

Use a for loop when you know exactly how many times you want to iterate through a block of code.

// 1. Initialize counter (int i = 0); 2. Check condition (i < 5); 3. Increment (i++)
for (int i = 0; i < 5; i++) {
  // This will print 0, 1, 2, 3, 4
  System.out.println("Iteration count: " + i);
}

  1. The While Loop

Use a while loop when the number of iterations is unknown and deeply reliant on a dynamic condition. It checks the condition before running.

int counter = 0;
while (counter < 3) {
    System.out.println(counter);
    counter++; // If you forget this, the loop runs forever!
}

  1. The Do-While Loop

A do-while loop is similar to a while loop, but it evaluates its condition at the end of the block instead of the beginning. This guarantees the code block will be executed at least once, even if the condition is false from the start.

int pass = 0;
do {
    System.out.println("This runs once no matter what!");
    pass++;
} while (pass < 0); // Condition is false, loop terminates after 1 run.

[!CAUTION] Infinite Loops: Always double-check your loop conditions. An infinite while (true) loop without a break statement will freeze your application entirely and cause a catastrophic CPU spike.

Writing Conditions That Stay Readable

Control flow becomes hard when conditions try to do too much in one line. A clean Java program usually gives complex decisions a meaningful name before using them in an if statement.

int age = 21;
boolean hasVerifiedEmail = true;
boolean isEligible = age >= 18 && hasVerifiedEmail;

if (isEligible) {
    System.out.println("Account can be activated");
}

This style is easier to debug because you can print or inspect isEligible directly. It also reads closer to the business rule.

Loop Choice Guide

NeedUseExample
Known number of iterationsforPrint 1 to 10
Unknown count, condition-firstwhileRead until valid input
Run at least oncedo-whileShow a menu once before asking again
Visit every itemEnhanced forPrint every name in an array

Guard Clauses

Sometimes it is cleaner to handle invalid cases early instead of nesting multiple levels of if.

static void printDiscount(int age) {
    if (age < 0) {
        System.out.println("Invalid age");
        return;
    }

    if (age >= 60) {
        System.out.println("Senior discount");
    } else {
        System.out.println("Standard price");
    }
}

Common Mistakes

  • Using = instead of == in conditions.
  • Forgetting break in older switch syntax.
  • Creating infinite loops by forgetting to update the loop variable.
  • Writing deeply nested conditions that could be simplified with early returns.

Mini Practice

Write a program that prints grades from marks: 90+ A, 75+ B, 60+ C, otherwise D. Then rewrite it using named boolean variables such as isExcellent and isGood.

Practice Lab: Grade and Eligibility Checker

Use conditions and loops together in one small program.

  1. Create an array of five marks.
  2. Loop through each mark.
  3. Print Pass for marks 40 and above, otherwise Fail.
  4. Add grade bands: A for 90+, B for 75+, C for 60+, D for 40+.
  5. Count how many students passed.

Goal: Practice if, else if, comparison operators, and loop repetition in one flow.

Revision Checkpoint

  • if: Use for boolean decisions.
  • else if: Use for ordered conditions where the first match wins.
  • switch: Use for clear fixed-value branching.
  • for: Use when the iteration count is known.
  • while: Use when repetition depends on a condition.

Before the quiz: Identify whether a problem needs a decision, a counted loop, or a condition-based loop.

Share this article

Share on TwitterShare on LinkedInShare on FacebookShare on WhatsAppShare on Email

Test your knowledge

Take a quick quiz based on this chapter.

mediumJava
Quiz: Control Flow
10 questions5 min
Lesson 3 of 10 in 1. Java Fundamentals
Previous in 1. Java Fundamentals
2. Data Types & Variables
Next in 1. Java Fundamentals
4. String Manipulation in Depth
Back to Java Programming: From Zero to Enterprise
Back to moduleCategories