AI Hints
Home›Java Tutorial›Comparison Operators, if, else and else if
Java · Lesson 29 of 120

if

Run code only sometimes.

⏱ 2 min read▶ Video at 37:50🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

An if statement runs some code, only when a condition is true. If it isn't true, Java skips that code, and carries on.

  • A condition
  • True: run the block
  • False: skip it

When it is true

If, then a condition in round brackets. If the condition is true, Java runs everything inside the curly braces. Then it carries on after them, either way. Temperature is thirty one, so the condition is true. Run it. Both warnings print, then the goodbye.

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

When it is false

Now the temperature is twenty two. The condition is false, so the whole block is skipped. Run it. Only the last line prints.

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

if rules

The condition always goes in round brackets. The code to run goes in curly braces. Indent the code inside, so it's easy to see what belongs to the if. And always use braces, even for one line. It prevents mistakes.

keyvalue
( condition )round brackets
{ code }curly braces
Indentthe inside
Alwaysuse braces

Summary

If runs a block of code, only when its condition is true. Otherwise, Java skips it. Next, else, and else if.

Key takeaways
  • if (condition) { }
  • True: runs
  • False: skipped
Next up: else and else if — one path or another