Conditional Statements

Conditional statements allow your program to make decisions and execute different code based on certain conditions. They are fundamental to creating dynamic and responsive programs.

1. if Statement

The if statement executes a block of code only if a specified condition is true.

int age = 18;

if (age >= 18) {
    System.out.println("You are eligible to vote");
}

// Output: You are eligible to vote

2. if-else Statement

The if-else statement provides an alternative block of code when the condition is false.

int marks = 45;

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

// Output: Fail

3. if-else-if Ladder

Use if-else-if to test multiple conditions in sequence.

int marks = 75;

if (marks >= 90) {
    System.out.println("Grade: A+");
} else if (marks >= 80) {
    System.out.println("Grade: A");
} else if (marks >= 70) {
    System.out.println("Grade: B");
} else if (marks >= 60) {
    System.out.println("Grade: C");
} else {
    System.out.println("Grade: F");
}

// Output: Grade: B

4. switch-case Statement

The switch statement is used when you need to compare a variable against multiple values.

int day = 3;
String dayName;

switch (day) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    case 4:
        dayName = "Thursday";
        break;
    case 5:
        dayName = "Friday";
        break;
    case 6:
        dayName = "Saturday";
        break;
    case 7:
        dayName = "Sunday";
        break;
    default:
        dayName = "Invalid day";
        break;
}

System.out.println(dayName);  // Output: Wednesday

⚠️ Important: Always use break in each case to prevent fall-through!

5. Ternary Operator (?:)

The ternary operator is a shorthand for simple if-else statements.

Syntax: condition ? value_if_true : value_if_false

int age = 20;

// Using if-else
String result;
if (age >= 18) {
    result = "Adult";
} else {
    result = "Minor";
}

// Using ternary operator (shorter)
String result = (age >= 18) ? "Adult" : "Minor";
System.out.println(result);  // Output: Adult

// Another example
int a = 10, b = 20;
int max = (a > b) ? a : b;
System.out.println("Maximum: " + max);  // Output: Maximum: 20

Looping Statements

Loops allow you to execute a block of code repeatedly. Java provides three types of loops: for, while, and do-while.

1. for Loop

Use the for loop when you know exactly how many times you want to iterate.

Syntax: for (initialization; condition; update) { ... }

// Print numbers 1 to 5
for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}
// Output: 1 2 3 4 5

// Calculate sum of first 10 numbers
int sum = 0;
for (int i = 1; i <= 10; i++) {
    sum += i;
}
System.out.println("Sum: " + sum);  // Output: Sum: 55

2. while Loop

Use the while loop when you don't know in advance how many times to iterate. The condition is checked before each iteration.

// Print numbers 1 to 5
int i = 1;
while (i <= 5) {
    System.out.println(i);
    i++;
}
// Output: 1 2 3 4 5

// Find first power of 2 greater than 100
int num = 1;
while (num <= 100) {
    num *= 2;
}
System.out.println("First power of 2 > 100: " + num);  // Output: 128

3. do-while Loop

The do-while loop is similar to while, but the condition is checked after each iteration. This guarantees the loop executes at least once.

// Print numbers 1 to 5
int i = 1;
do {
    System.out.println(i);
    i++;
} while (i <= 5);
// Output: 1 2 3 4 5

// Example showing difference from while loop
int x = 10;
do {
    System.out.println("Executed once!");
} while (x < 5);
// Output: Executed once! (runs even though condition is false)

Key Difference:

  • while: Condition checked first, may not execute at all
  • do-while: Executes at least once, then checks condition

4. Enhanced for Loop (for-each)

Used to iterate through arrays or collections. Simpler syntax when you don't need the index.

int[] numbers = {10, 20, 30, 40, 50};

// Enhanced for loop
for (int num : numbers) {
    System.out.println(num);
}
// Output: 10 20 30 40 50

String[] fruits = {"Apple", "Banana", "Orange"};
for (String fruit : fruits) {
    System.out.println(fruit);
}

Loop Control Statements

Control statements allow you to change the normal flow of loop execution. Java provides break and continue statements for this purpose.

1. break Statement

The break statement terminates the loop immediately and transfers control to the statement following the loop.

// Find first number divisible by 7
for (int i = 1; i <= 100; i++) {
    if (i % 7 == 0) {
        System.out.println("First number divisible by 7: " + i);
        break;  // Exit the loop
    }
}
// Output: First number divisible by 7: 7

// Search for an element in array
int[] numbers = {10, 20, 30, 40, 50};
int search = 30;
boolean found = false;

for (int num : numbers) {
    if (num == search) {
        found = true;
        break;  // Stop searching once found
    }
}

if (found) {
    System.out.println(search + " found!");
}

2. continue Statement

The continue statement skips the current iteration and moves to the next iteration of the loop.

// Print only odd numbers from 1 to 10
for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        continue;  // Skip even numbers
    }
    System.out.println(i);
}
// Output: 1 3 5 7 9

// Skip negative numbers
int[] numbers = {5, -2, 10, -7, 15, -3, 20};
int sum = 0;

for (int num : numbers) {
    if (num < 0) {
        continue;  // Skip negative numbers
    }
    sum += num;
}

System.out.println("Sum of positive numbers: " + sum);  // Output: 50

📊 break vs continue

Statement Action Use Case
break Exits the entire loop When you've found what you're looking for
continue Skips to next iteration When you want to skip certain values

Blocks, Scope, and Variable Visibility

Understanding scope is crucial for writing correct programs. Scope determines where a variable can be accessed and how long it exists in memory.

1. Grouping Statements in Blocks

A block is a group of statements enclosed in curly braces { }. Blocks are used to group multiple statements together.

// Single statement - no braces needed
if (age >= 18)
    System.out.println("Adult");

// Multiple statements - braces required
if (age >= 18) {
    System.out.println("Adult");
    System.out.println("Can vote");
    System.out.println("Can drive");
}

// Nested blocks
{
    int x = 10;
    {
        int y = 20;
        System.out.println(x + y);  // Can access both x and y
    }
    // System.out.println(y);  // ERROR: y is not visible here
}

2. Variable Scope

Scope refers to the region of code where a variable is accessible.

Local Variables (Block Scope)

public class ScopeExample {
    public static void main(String[] args) {
        int x = 10;  // Scope: entire main method
        
        if (x > 5) {
            int y = 20;  // Scope: only inside this if block
            System.out.println(x + y);  // OK: both visible here
        }
        
        // System.out.println(y);  // ERROR: y not visible here
        System.out.println(x);  // OK: x still visible
    }
}

Loop Variable Scope

// Variable i is only visible inside the for loop
for (int i = 0; i < 5; i++) {
    System.out.println(i);
}
// System.out.println(i);  // ERROR: i not visible here

// Declare variable before loop to use it after
int j;
for (j = 0; j < 5; j++) {
    System.out.println(j);
}
System.out.println("Final value: " + j);  // OK: j is visible here

3. Class Variables vs Local Variables

public class VariableScope {
    // Class variable (instance variable)
    // Scope: entire class, visible to all methods
    int classVar = 100;
    
    public void method1() {
        // Local variable
        // Scope: only inside method1
        int localVar = 50;
        
        System.out.println(classVar);   // OK: class variable accessible
        System.out.println(localVar);   // OK: local variable accessible
    }
    
    public void method2() {
        System.out.println(classVar);   // OK: class variable accessible
        // System.out.println(localVar);  // ERROR: localVar not visible here
    }
}

4. Variable Shadowing

When a local variable has the same name as a class variable, the local variable "shadows" the class variable.

public class Shadowing {
    int x = 10;  // Class variable
    
    public void display() {
        int x = 20;  // Local variable shadows class variable
        
        System.out.println(x);        // Output: 20 (local variable)
        System.out.println(this.x);   // Output: 10 (class variable)
    }
}

⚠️ Best Practice: Avoid variable shadowing as it can make code confusing. Use different names for local and class variables.

📋 Scope Rules Summary

  • 1. Variables declared inside a block are only visible within that block
  • 2. Inner blocks can access variables from outer blocks
  • 3. Outer blocks cannot access variables from inner blocks
  • 4. Loop variables (for loop) are scoped to the loop
  • 5. Class variables are accessible throughout the class
  • 6. Local variables shadow class variables with the same name

Key Points to Remember

  • Use if-else for simple conditions, switch-case for multiple discrete values.
  • Ternary operator ?: is a shorthand for simple if-else statements.
  • Always use break in switch cases to prevent fall-through.
  • for loop: when you know iteration count; while: when you don't.
  • do-while executes at least once; while may not execute at all.
  • break exits the loop; continue skips to next iteration.
  • Variables are only visible within their scope (block where they're declared).
  • Inner blocks can access outer variables, but not vice versa.
  • Avoid variable shadowing to keep code clear and maintainable.