if and else

Asking questions

Comparison operators ask a yes/no question and answer with a boolean (true or false):

OperatorQuestionExampleAnswer
==equal?5 == 5true
!=not equal?5 != 3true
>bigger?2 > 7false
<smaller?2 < 7true
>=bigger or equal?7 >= 7true
<=smaller or equal?8 <= 7false

if: do something only when...

Code inside an if runs only when the condition in brackets is true:

public class Main {
    public static void main(String[] args) {
        int temperature = 35;
        if (temperature > 30) {
            System.out.println("It's hot! Drink water.");
        }
        System.out.println("Have a nice day.");
    }
}

Output

It's hot! Drink water.
Have a nice day.

else: otherwise...

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int age = sc.nextInt();
        if (age >= 18) {
            System.out.println("You can vote.");
        } else {
            System.out.println("Too young to vote.");
        }
    }
}

Input (what the user types)

15

Output

Too young to vote.

Think of it like this: if/else is like a fork in the road: you go left or right, never both.

else if: more than two choices

Java checks each condition from top to bottom and runs the first one that is true:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int marks = sc.nextInt();
        if (marks >= 90) {
            System.out.println("Grade A");
        } else if (marks >= 75) {
            System.out.println("Grade B");
        } else if (marks >= 50) {
            System.out.println("Grade C");
        } else {
            System.out.println("Try again");
        }
    }
}

Input (what the user types)

82

Output

Grade B

82 is not ≥ 90, but it is ≥ 75, so Java prints Grade B and skips the rest.

Common mistake: Don't put a semicolon after the condition: if (x > 5); ends the if right there, so the block below always runs.

Tip: Always use curly brackets { }, even for one line. It prevents confusing bugs later.

HOME LABS COMMUNITY DASHBOARD