java chapter3

🔹 1. What are Control Statements?

Control statements determine the flow of execution of a program — i.e., which statements are executedin what order, and how many times.

Java control statements are divided into three main types:

  1. Decision-making statements
  2. Looping statements
  3. Jump (branching) statements

🧩 1. Decision-Making Statements

Used to make choices based on conditions.

🟢 A. if Statement

Executes a block only if the condition is true.

if (marks >= 33) {
    System.out.println("Pass");
}

🟢 B. if–else Statement

Executes one block if condition is true, otherwise another.

if (marks >= 33) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}

🟢 C. if–else–if Ladder

Used when there are multiple conditions.

if (marks >= 90)
    System.out.println("Grade A");
else if (marks >= 75)
    System.out.println("Grade B");
else
    System.out.println("Grade C");

🟢 D. Nested if

One if inside another.

if (a > 0) {
    if (a % 2 == 0)
        System.out.println("Positive Even");
}

🟢 E. switch Statement

Used for multi-way branching when many conditions depend on one variable.

switch(day) {
    case 1: System.out.println("Monday"); break;
    case 2: System.out.println("Tuesday"); break;
    ...
    default: System.out.println("Invalid day");
}

✅ Must include break to stop fall-through.


🔁 2. Looping Statements (Iteration)

Used to execute a block of code repeatedly.

🔵 A. while Loop

Condition is checked before the loop executes.

int i = 1;
while (i <= 5) {
    System.out.println(i);
    i++;
}

🔵 B. do–while Loop

Condition is checked after execution — runs at least once.

int i = 1;
do {
    System.out.println(i);
    i++;
} while (i <= 5);

🔵 C. for Loop

Used when the number of iterations is known.

for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}

🔵 D. Enhanced for Loop (for-each)

Used for arrays and collections.

int nums[] = {1, 2, 3, 4};
for (int x : nums) {
    System.out.println(x);
}

🔀 3. Jump Statements

Used to change the normal sequence of execution.

🟣 A. break

  • Used to exit a loop or switch.
for (int i = 1; i <= 10; i++) {
    if (i == 5) break;
    System.out.println(i);
}

🟣 B. continue

  • Skips current iteration and jumps to the next loop cycle.
for (int i = 1; i <= 5; i++) {
    if (i == 3) continue;
    System.out.println(i);
}

🟣 C. return

  • Exits from a method and optionally returns a value.
return;  
// or
return value;

⚙️ 4. Nested Loops

Loop inside another loop.

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        System.out.print("* ");
    }
    System.out.println();
}

Leave a Comment

Your email address will not be published. Required fields are marked *