0
0
Javaprogramming~5 mins

If statement in Java

Choose your learning style9 modes available
Introduction

An if statement helps your program make choices by running code only when a condition is true.

To check if a user is old enough to access a website.
To decide if a number is positive or negative.
To turn on a light only when it is dark.
To give a discount if a customer buys more than 5 items.
Syntax
Java
if (condition) {
    // code to run if condition is true
}

The condition is a true or false question.

Curly braces { } group the code that runs when true.

Examples
This checks if age is 18 or more, then prints a message.
Java
if (age >= 18) {
    System.out.println("You can vote.");
}
This runs the message only if score is greater than 50.
Java
if (score > 50) {
    System.out.println("You passed!");
}
This prints a reminder if isRaining is true.
Java
if (isRaining) {
    System.out.println("Take an umbrella.");
}
Sample Program

This program checks if the temperature is above 25 degrees. If yes, it prints a message.

Java
public class Main {
    public static void main(String[] args) {
        int temperature = 30;
        if (temperature > 25) {
            System.out.println("It's hot outside.");
        }
    }
}
OutputSuccess
Important Notes

If the condition is false, the code inside if does not run.

You can add else to run code when the condition is false.

Summary

If statements let your program choose actions based on conditions.

Use if (condition) { ... } to run code only when the condition is true.

Conditions are questions that answer true or false.