← Back to Chapters

Java if-else Statement

? Java if-else Statement

? Quick Overview

The if-else statement in Java is used to make decisions based on conditions. It allows the program to execute different blocks of code depending on whether a condition is true or false.

? Key Concepts

  • Conditions must evaluate to true or false
  • Uses relational and logical operators
  • Supports multiple branches using else if
  • Controls program flow

? Syntax / Theory

Java evaluates the condition inside the if statement. If it is true, the if block runs; otherwise, the else block executes.

? View Code Example
// Basic if-else example in Java
int age = 20;

if (age >= 18) {
    System.out.println("Eligible to vote");
} else {
    System.out.println("Not eligible to vote");
}

? Live Output / Explanation

Output

If age is 20, the condition age >= 18 is true, so the output will be:

Eligible to vote

? Interactive Demo

Scenario: Simulate the Java code above. Change the variable age and run the logic.

int age = ;
// Click 'Run Code' to see output...

✅ Tips & Best Practices

  • Always use meaningful conditions
  • Keep conditional logic simple and readable
  • Use braces { } even for single statements
  • Avoid deeply nested if-else blocks

? Try It Yourself

  • Positive/Negative: Write a program that checks whether a number is positive, negative, or zero using if-else if.
  • Even or Odd: Check if a given integer variable is even or odd using the modulus operator %.
  • Grade Calculator: Assign a grade (A, B, C, F) based on a score variable (e.g., if score > 90 print "A").
  • Leap Year: Write a program to determine if a given year is a leap year.