CACS204 Object Oriented Programming in Java

Object Oriented Programming in JavaUnit 312 min read

Control Statements in Java: Loops, Conditionals & Decision-Making

Unit 3 of Object Oriented Programming in Java covers if-else, switch-case, for/while/do-while loops, nested control structures, and break/continue statements with real-world applications, code examples, and step-by-step traces to master decision-making and iteration in Java programs.

Core Concepts & Definitions

Control statements determine the flow of execution in a program by:

  1. Making decisions (if-else, switch-case).
  2. Repeating tasks (loops: for, while, do-while).
  3. Terminating loops early (break, continue).
-2-1.5-1-0.50.511.520.511.52xyDecision boundary (if-else)x=0 → elsex>0 → true
Graphical decision boundaries for conditional statements

1. Decision-Making Statements

A. if Statement
  • Executes a block if a condition is true.
  • Syntax:
    if (condition) {
        // code to execute if true
    }
    
  • Example: Check if a number is positive.
    int num = 5;
    if (num > 0) {
        System.out.println("Positive");
    }
    
    Trace:
    Step num Condition (num > 0) Output
    1 5 true "Positive"
B. if-else Statement
  • Executes one block if true, another if false.
  • Syntax:
    if (condition) {
        // true block
    } else {
        // false block
    }
    
  • Example: Check even/odd (real-world tie: eSewa transaction validation).
    int amount = 1000;
    if (amount % 2 == 0) {
        System.out.println("Even: Valid transaction");
    } else {
        System.out.println("Odd: Invalid amount");
    }
    
    Trace:
    Step amount amount % 2 Condition Output
    1 1000 0 true "Even: Valid transaction"
C. Nested if-else
  • Multiple conditions checked sequentially.
  • Example: Grade calculator (real-world tie: NTC exam grading).
    int marks = 85;
    if (marks >= 90) {
        System.out.println("A");
    } else if (marks >= 80) {
        System.out.println("B");
    } else {
        System.out.println("C");
    }
    
    Trace:
    Step marks Condition 1 (>=90) Condition 2 (>=80) Output
    1 85 false true "B"
D. switch-case
  • Efficient for multiple discrete choices.
  • Syntax:
    switch (variable) {
        case value1: // code; break;
        case value2: // code; break;
        default:     // fallback
    }
    
  • Example: Day-of-week printer (real-world tie: Pathao driver shifts).
    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("Invalid day");
    }
    
    Trace:
    Step day Matched Case Output
    1 3 case 3 "Wednesday"

2. Looping Statements

Loops repeat code blocks until a condition is met.

A. for Loop

  • Used for known iterations (e.g., arrays, fixed counts).
  • Syntax:
    for (initialization; condition; update) {
        // loop body
    }
    
  • Example: Print numbers 1–5 (real-world tie: Daraz order IDs).
    for (int i = 1; i <= 5; i++) {
        System.out.println("Order ID: " + i);
    }
    
    Trace:
    Iteration i Condition (i <= 5) Output
    1 1 true "Order ID: 1"
    2 2 true "Order ID: 2"
    ... ... ... ...
    5 5 true "Order ID: 5"
    6 6 false Loop ends

B. while Loop

  • Runs while a condition is true (unknown iterations).
  • Syntax:
    while (condition) {
        // loop body
    }
    
  • Example: Sum digits of a number (real-world tie: Khalti transaction fees).
    int num = 1234, sum = 0;
    while (num > 0) {
        sum += num % 10;
        num /= 10;
    }
    System.out.println("Sum: " + sum); // Output: 10
    
    Trace:
    Step num num % 10 sum num /= 10 Condition (num > 0)
    1 1234 4 4 123 true
    2 123 3 7 12 true
    3 12 2 9 1 true
    4 1 1 10 0 true
    5 0 0 10 0 false (loop ends)

C. do-while Loop

  • Guarantees at least one execution (condition checked after).
  • Syntax:
    do {
        // loop body
    } while (condition);
    
  • Example: Password retry (real-world tie: Ncell login system).
    String password = "";
    do {
        System.out.print("Enter password: ");
        password = "1234"; // Assume user input
    } while (!password.equals("1234"));
    System.out.println("Access granted!");
    
    Trace:
    Iteration password Condition (!="1234") Output
    1 "1234" false "Access granted!"
    (Note: Loop runs once even if condition is false initially.)

3. Loop Control Statements

A. break

  • Exits the loop immediately.
  • Example: Stop at first even number.
    for (int i = 1; i <= 5; i++) {
        if (i % 2 == 0) break;
        System.out.println(i);
    }
    
    Trace:
    Iteration i i % 2 Condition Output Action
    1 1 1 false 1 Continue
    2 2 0 true - Break

B. continue

  • Skips current iteration.
  • Example: Print odd numbers only.
    for (int i = 1; i <= 5; i++) {
        if (i % 2 == 0) continue;
        System.out.println(i);
    }
    
    Trace:
    Iteration i i % 2 Condition Output Action
    1 1 1 false 1 Continue
    2 2 0 true - Continue
    3 3 1 false 3 Continue

## In the Real World

  1. eSewa Transaction Validation

    • Uses if-else to check amount validity (e.g., if (amount > 0 && amount <= balance)).
    • Switch-case for payment method selection (e.g., switch (method) { case "Khalti": ... }).
  2. Pathao Driver Shifts

    • for loops iterate through daily ride requests (for (Ride r : rides) { ... }).
    • break exits the loop if the driver’s shift ends (if (currentTime > shiftEnd) break;).
  3. NTC Exam Grading

    • Nested if-else determines grade letters based on marks:
      if (marks >= 80) grade = 'A';
      else if (marks >= 60) grade = 'B';
      else grade = 'C';
      
  4. Khalti Transaction Fees

    • while loop calculates total fees by summing percentages:
      while (amount > 0) {
          fee += amount * 0.02; // 2% fee
          amount -= 100;        // Process in chunks
      }
      
  5. Daraz Order Queue

    • do-while ensures at least one order is processed before checking stock:
      do {
          processOrder();
      } while (inventory > 0);
      

## Visualizing Control Flow

1. Decision Tree for Even/Odd Check

flowchart TD
    A["Start"] --> B["Is number % 2 == 0?"]
    B -->|"Yes"| C["Print 'Even'"]
    B -->|"No"| D["Print 'Odd'"]
    C --> E["End"]
    D --> E

2. for Loop Execution (1–5)

0123456i=1 (print)i=2 (print)i=3 (print)i=4 (print)i=5 (print)Loop ends (i > 5)
for (int i = 1; i <= 5; i++) execution steps

3. Stack Simulation with break

321TOP
Step 1: i=1 (odd) → stack unchanged

4. Linked List Traversal with continue

head10203040NULL
Linked list traversal: even node (20) skipped via `continue`

## Comparison Table: Control Statements

Statement Use Case Syntax Example Key Feature
if Single condition check if (x > 0) { ... } No else block
if-else Two-way decision if (x > 0) else { ... } Executes one block
switch-case Multi-way discrete choices switch (day) { case 1: ... } Efficient for constants
for Known iterations for (int i=0; i<5; i++) { ... } Initialization, update, condition
while Unknown iterations (pre-check) while (x > 0) { ... } May not run
do-while Unknown iterations (post-check) do { ... } while (x > 0); Runs at least once
break Exit loop immediately if (x == 0) break; Terminates enclosing loop
continue Skip current iteration if (x % 2 == 0) continue; Jumps to next iteration

## Common Pitfalls & Best Practices

  1. Off-by-One Errors

    • Problem: for (int i=0; i<=10; i++) runs 11 times (0–10).
    • Fix: Use < for upper bounds: i < 10.
  2. Infinite Loops

    • Cause: Missing update in while or for (e.g., while (true) without break).
    • Fix: Always update loop variables (e.g., i++, num--).
  3. Switch-Case Fallthrough

    • Problem: Missing break causes unintended execution of next cases.
    • Fix: Add break after each case (except default).
  4. Nested Loops Clarity

    • Problem: Complex nested loops are hard to debug.
    • Fix: Use meaningful variable names (e.g., for (User u : users)).

## Exam Tip

  1. Code Tracing Questions

    • Expect: "Trace the output of the following code."
    • Strategy:
      • Write a step-by-step table (like above).
      • Highlight loop counters and conditions.
      • Example:
        for (int i=2; i<=6; i+=2) System.out.print(i);
        
        Trace:
        Iteration i Condition (i<=6) Output
        1 2 true 2
        2 4 true 4
        3 6 true 6
        4 8 false -
  2. GUI-Based Questions

    • Expect: "Design a form to check even/odd."
    • Strategy:
      • Use if-else with JOptionPane or JTextField.
      • Example:
        int num = Integer.parseInt(JOptionPane.showInputDialog("Enter number:"));
        if (num % 2 == 0) JOptionPane.showMessageDialog(null, "Even");
        else JOptionPane.showMessageDialog(null, "Odd");
        
  3. Real-World Scenarios

    • Expect: "How would you use loops in [eSewa/Khalti]?"
    • Answer:
      • eSewa: while loop for transaction validation (check balance, retry on failure).
      • Khalti: for loop to process multiple payments in a batch.
  4. Short-Answer Definitions

    • Key Terms to Memorize:
      • Loop: Repeats code until a condition is false.
      • Nested if: if inside another if for hierarchical checks.
      • Infinite loop: Loop with no exit condition (e.g., while (true)).

## Practice Problems

  1. Trace the Output:

    int x = 5;
    while (x > 0) {
        System.out.print(x--);
    }
    

    Answer: 54321

  2. Fix the Code:

    for (int i=0; i<5; i++) {
        if (i == 2) continue;
        System.out.print(i);
    }
    

    Output: 0134 (skips 2).

  3. Real-World Application:

    • Write a switch-case to handle Ncell recharge options (e.g., case "100": charge(100); break;).
  4. Debugging:

    • Why does this loop run infinitely?
      int i = 0;
      while (i < 5) {
          System.out.println(i);
      }
      

    Answer: Missing i++ (counter never updates). Fix: while (i < 5) { ...; i++; }.

Based on the TU BCA syllabus for Object Oriented Programming in Java (CACS204), unit 3.

Discussion

Loading…