CodeBlanks Logo Icon CodeBlanks

The if statement

Learn condition checks with if.

The if statement

The if statement runs a block when a condition is true. The condition is written in parentheses and must evaluate to a boolean.

int score = 75;
if (score >= 50) {
    System.out.println("Pass");
}

If the condition is true, the code inside the braces runs; if false, it is skipped. Comparison operators are >, <, >=, <=, == and !=. Braces are optional for one-line blocks but recommended for readability.

Block and comparison

An if block is delimited by braces. The condition uses comparison operators:

int age = 20;
if (age >= 18) {
    System.out.println("Can drive");
}

Operators: > greater, < less, >= greater or equal, <= less or equal, == equal, != not equal. Conditions can be combined with logical operators: && and, || or.

Practice Temperature check with if

Write a Main class with a main method. Assign 32 to int temp. Inside if (temp > 30) print System.out.println("Hot").

Sample solution

Main.java
public class Main {
    public static void main(String[] args) {
        int temp = 32;
        if (temp > 30) {
            System.out.println("Hot");
        }
    }
}

Expected output

Hot

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When does if (score >= 50) return true?

  • When score is below 50
  • When score is 50 or above Correct answer
  • Always
  • When score is 0

Explanation: >= includes 50 and above.

2 Complete the if condition

Question
int score = 75;
if (score ____ 50) {
    System.out.println("Pass");
}
Answer
int score = 75;
if (score >= 50) {
    System.out.println("Pass");
}

Explanation: Use >= for greater-or-equal.

3 Match the if concepts

Term Meaning
if Condition
( ) Parens
{ } Block
true Runs

All lessons in Beginner