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:
- Making decisions (if-else, switch-case).
- Repeating tasks (loops: for, while, do-while).
- Terminating loops early (break, continue).
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.
Trace:int num = 5; if (num > 0) { System.out.println("Positive"); }Step numCondition ( 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).
Trace:int amount = 1000; if (amount % 2 == 0) { System.out.println("Even: Valid transaction"); } else { System.out.println("Odd: Invalid amount"); }Step amountamount % 2Condition 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).
Trace:int marks = 85; if (marks >= 90) { System.out.println("A"); } else if (marks >= 80) { System.out.println("B"); } else { System.out.println("C"); }Step marksCondition 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).
Trace: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"); }Step dayMatched 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).
Trace:for (int i = 1; i <= 5; i++) { System.out.println("Order ID: " + i); }Iteration iCondition ( 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).
Trace:int num = 1234, sum = 0; while (num > 0) { sum += num % 10; num /= 10; } System.out.println("Sum: " + sum); // Output: 10Step numnum % 10sumnum /= 10Condition ( 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).
Trace:String password = ""; do { System.out.print("Enter password: "); password = "1234"; // Assume user input } while (!password.equals("1234")); System.out.println("Access granted!");Iteration passwordCondition ( !="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.
Trace:for (int i = 1; i <= 5; i++) { if (i % 2 == 0) break; System.out.println(i); }Iteration ii % 2Condition Output Action 1 1 1 false 1 Continue 2 2 0 true - Break
B. continue
- Skips current iteration.
- Example: Print odd numbers only.
Trace:for (int i = 1; i <= 5; i++) { if (i % 2 == 0) continue; System.out.println(i); }Iteration ii % 2Condition Output Action 1 1 1 false 1 Continue 2 2 0 true - Continue 3 3 1 false 3 Continue
## In the Real World
eSewa Transaction Validation
- Uses
if-elseto check amount validity (e.g.,if (amount > 0 && amount <= balance)). - Switch-case for payment method selection (e.g.,
switch (method) { case "Khalti": ... }).
- Uses
Pathao Driver Shifts
forloops iterate through daily ride requests (for (Ride r : rides) { ... }).breakexits the loop if the driver’s shift ends (if (currentTime > shiftEnd) break;).
NTC Exam Grading
- Nested
if-elsedetermines grade letters based on marks:if (marks >= 80) grade = 'A'; else if (marks >= 60) grade = 'B'; else grade = 'C';
- Nested
Khalti Transaction Fees
whileloop calculates total fees by summing percentages:while (amount > 0) { fee += amount * 0.02; // 2% fee amount -= 100; // Process in chunks }
Daraz Order Queue
do-whileensures 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 --> E2. for Loop Execution (1–5)
3. Stack Simulation with break
4. Linked List Traversal with 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
Off-by-One Errors
- Problem:
for (int i=0; i<=10; i++)runs 11 times (0–10). - Fix: Use
<for upper bounds:i < 10.
- Problem:
Infinite Loops
- Cause: Missing update in
whileorfor(e.g.,while (true)withoutbreak). - Fix: Always update loop variables (e.g.,
i++,num--).
- Cause: Missing update in
Switch-Case Fallthrough
- Problem: Missing
breakcauses unintended execution of next cases. - Fix: Add
breakafter each case (exceptdefault).
- Problem: Missing
Nested Loops Clarity
- Problem: Complex nested loops are hard to debug.
- Fix: Use meaningful variable names (e.g.,
for (User u : users)).
## Exam Tip
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:
Trace:for (int i=2; i<=6; i+=2) System.out.print(i);Iteration iCondition ( i<=6)Output 1 2 true 2 2 4 true 4 3 6 true 6 4 8 false -
GUI-Based Questions
- Expect: "Design a form to check even/odd."
- Strategy:
- Use
if-elsewithJOptionPaneorJTextField. - Example:
int num = Integer.parseInt(JOptionPane.showInputDialog("Enter number:")); if (num % 2 == 0) JOptionPane.showMessageDialog(null, "Even"); else JOptionPane.showMessageDialog(null, "Odd");
- Use
Real-World Scenarios
- Expect: "How would you use loops in [eSewa/Khalti]?"
- Answer:
- eSewa:
whileloop for transaction validation (check balance, retry on failure). - Khalti:
forloop to process multiple payments in a batch.
- eSewa:
Short-Answer Definitions
- Key Terms to Memorize:
- Loop: Repeats code until a condition is false.
- Nested
if:ifinside anotheriffor hierarchical checks. - Infinite loop: Loop with no exit condition (e.g.,
while (true)).
- Key Terms to Memorize:
## Practice Problems
Trace the Output:
int x = 5; while (x > 0) { System.out.print(x--); }Answer:
54321Fix the Code:
for (int i=0; i<5; i++) { if (i == 2) continue; System.out.print(i); }Output:
0134(skips2).Real-World Application:
- Write a
switch-caseto handle Ncell recharge options (e.g.,case "100": charge(100); break;).
- Write a
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++; }.- Why does this loop run infinitely?
Based on the TU BCA syllabus for Object Oriented Programming in Java (CACS204), unit 3.
Discussion
Loading…