Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Lesson 3: Control Flow — Selection, Iteration & Jump Statements

Lesson 4 of 18 in the free Programming in Java notes on Siksha Sarovar, written by Rohit Jangra.

3.1 Selection: if, if-else, else-if Ladder

if (marks >= 90)      grade = 'A';
else if (marks >= 75) grade = 'B';
else if (marks >= 60) grade = 'C';
else                  grade = 'F';

The condition must be booleanif (x = 5) is a compile error in Java (unlike C, where it is a silent bug). The dangling else binds to the nearest unmatched if, so always use braces.

3.2 switch — Classic vs Arrow Form

Classic switch works on int-compatible types (byte, short, char, int), String (since Java 7), enums, and wrapper types — not long, float, double, or boolean.

switch (day) {
    case 1:
    case 7:  System.out.println("Weekend"); break;
    case 2:  System.out.println("Monday");  break;   // forget break => fall-through!
    default: System.out.println("Weekday");
}

Fall-through is the number-one trap: without break, execution continues into the next case, even default.

Arrow switch (Java 14+) eliminates fall-through and can be an expression that yields a value:

String type = switch (day) {
    case 1, 7      -> "Weekend";
    case 2, 3, 4, 5, 6 -> "Weekday";
    default        -> {
        System.out.println("Invalid input");
        yield "Unknown";              // yield returns a value from a block
    }
};
FeatureClassic switchArrow switch
Fall-throughYes (needs break)Never
Multiple labels per caseVia stacked casescase 1, 7 ->
Usable as expressionNoYes (yield in blocks)
Exhaustiveness checkedNoYes, for expressions

3.3 Iteration: while, do-while, for, for-each

LoopTest positionMinimum executionsBest for
whileEntry (top)0Unknown iteration count
do-whileExit (bottom)1Menus, "ask again" input
forEntry0Known count / counters
for-each0Traversing arrays/collections
for (int i = 1; i <= 3; i++) System.out.print(i + " ");   // 1 2 3
int[] arr = {10, 20, 30};
for (int v : arr) System.out.print(v + " ");              // 10 20 30

for-each limitations (exam favourite): no index available, cannot modify the array slot through the loop variable, traverses forward only. All three sections of a classic for are optional — for(;;) is an infinite loop.

3.4 Jump Statements: break, continue, Labels

  • break exits the innermost loop or switch.
  • continue skips to the next iteration.
  • A label lets you break/continue an outer loop — the only sanctioned "goto-like" jump in Java:
outer:
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        if (i * j == 4) break outer;   // leaves BOTH loops
        System.out.println(i + "," + j);
    }
}

Output:

1,1
1,2
1,3
2,1

3.5 Classic Loop Patterns (Write-a-Program Bank)

Reverse digits / palindrome number:

int n = 121, rev = 0, t = n;
while (t != 0) { rev = rev * 10 + t % 10; t /= 10; }
System.out.println(n == rev ? "Palindrome" : "Not palindrome");

Prime check (trial division up to √n):

boolean prime = n > 1;
for (int i = 2; i * i <= n; i++)
    if (n % i == 0) { prime = false; break; }

Pyramid pattern (nested loops — printed in the code snippet below), Fibonacci series, Armstrong numbers, and factorial round out the standard exam bank. Master the pattern skeleton: outer loop = rows, inner loop(s) = spaces then symbols.

🎯 Exam Focus

  1. Compare while and do-while loops. Write a menu-driven program using do-while and switch.
  2. What is fall-through in switch? How does the arrow (->) form of switch eliminate it? Which data types are NOT allowed in a switch expression?
  3. Explain labelled break and continue with a nested-loop example and its exact output.
  4. Write a program to check whether a number is prime, and another to print all Armstrong numbers between 1 and 1000.
  5. Write a program to print a pyramid of stars of height n using nested loops.
  6. Predict the output of a switch with missing break statements (fall-through trace).