0
0
Javaprogramming~5 mins

If–else statement in Java

Choose your learning style9 modes available
Introduction

An if-else statement helps your program make choices. It runs one set of instructions if something is true, and another set if it is false.

Deciding if a user is old enough to sign up for a website.
Checking if a number is positive or negative before printing a message.
Choosing what message to show based on the time of day.
Turning on a light if it is dark, or turning it off if it is bright.
Syntax
Java
if (condition) {
    // code to run if condition is true
} else {
    // code to run if condition is false
}
The condition is a question your program asks that can be true or false.
Use curly braces { } to group the code that runs for each case.
Examples
This checks if age is 18 or more. If yes, it prints a voting message. Otherwise, it prints a different message.
Java
if (age >= 18) {
    System.out.println("You can vote.");
} else {
    System.out.println("You are too young to vote.");
}
This decides if the score is above 50 to print a pass or fail message.
Java
if (score > 50) {
    System.out.println("You passed!");
} else {
    System.out.println("Try again.");
}
Sample Program

This program checks if the temperature is above 25 degrees. It prints a message about the weather based on that.

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

Always use == to compare values, not =, which assigns values.

You can add more choices using else if for multiple conditions.

Summary

If-else lets your program pick between two paths.

Use it to run code when a condition is true, and different code when false.

Remember to use curly braces to keep your code clear and organized.