JavaIf-Else

Java If-Else

What is if-else?

In Java, the if-else statement helps your program make decisions. It checks if a condition is true or false, and then decides what to do next.

If it’s raining, take an umbrella. Otherwise, wear sunglasses.
Basic Structure

Java
if (condition) {
    // runs if the condition is true
} else {
    // runs if the condition is false
}

Example

Java
int number = 10;

if (number > 0) {
    System.out.println("The number is positive.");
} else {
    System.out.println("The number is not positive.");
}
The number is positive.
if – else if – else (Multiple Choices)

When you have more than one condition, use else if.

Java
int marks = 82;

if (marks >= 90) {
    System.out.println("Grade: A");
} else if (marks >= 75) {
    System.out.println("Grade: B");
} else if (marks >= 60) {
    System.out.println("Grade: C");
} else {
    System.out.println("Grade: F");
}
Grade: B
Success
The program checks conditions in order — the first one that’s true gets executed.
Nested if (if inside another if)

You can also put one if inside another — this is called a nested if.

Java
int age = 20;
boolean hasID = true;

if (age >= 18) {
    if (hasID) {
        System.out.println("You can enter the club.");
    } else {
        System.out.println("You need an ID to enter.");
    }
} else {
    System.out.println("You are too young to enter.");
}
You can enter the club.
Ternary Operator – Short Form

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

Java
int num = -5;
String result = (num > 0) ? "Positive" : "Negative or Zero";
System.out.println(result);
Negative or Zero
Note
Read it as: If num > 0, use "Positive", otherwise use "Negative or Zero".
Common Mistakes to Avoid

Mistake

Correct

if x > 5

if (x > 5)

if (x = 5) (assigns value)

if (x == 5) (compares value)

Forgetting curly braces {}

Always use {} for clarity

Practice Time!
  1. Check if a number is even or odd.

  2. Check if someone can vote (age ≥ 18).

  3. Find the largest of two numbers.

  4. Check if a year is a leap year.

  5. Create a simple grading system based on marks.

Summary

Keyword

Meaning

if

Checks a condition

else if

Adds another condition to check

else

Runs if none of the above are true

? :

Ternary operator (short if-else)