Java If...Else


In Java, the if...else statement is a conditional control structure used to make decisions in a program. It allows your code to execute different actions depending on whether a condition is true or false. Simply put, it helps your program “think” and “choose” what to do next.

For example, if a user enters a correct password, the program grants access; otherwise, it denies it. The if...else structure is one of the most basic and important parts of any programming logic.

The Basic Structure of If Statement

The simplest form of decision-making in Java starts with the if statement. It checks a condition, and if that condition is true, the block of code inside it runs. If the condition is false, the code is skipped.

Syntax:

if (condition) {
    // code to execute if condition is true
}

Example:

int number = 10;
if (number > 5) {
    System.out.println("The number is greater than 5.");
}

Here, the condition number > 5 is true, so the message prints. If it were false, nothing would happen.

The If...Else Statement

When you want to perform one action if the condition is true and another if it’s false, you use the if...else statement.

Syntax:

if (condition) {
    // code runs if condition is true
} else {
    // code runs if condition is false
}

Example:

int age = 17;
if (age >= 18) {
    System.out.println("You are eligible to vote.");
} else {
    System.out.println("You are not eligible to vote yet.");
}

In this example, the else block runs because the condition is false.

The If...Else If...Else Ladder

Sometimes, you need to test multiple conditions. In such cases, you can use the if...else if...else ladder. The program checks each condition in order, and as soon as one is true, the corresponding block executes, and the rest are ignored.

Syntax:

if (condition1) {
    // code for condition1
} else if (condition2) {
    // code for condition2
} else {
    // code if none are true
}

Example:

int marks = 72;

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("Fail");
}

Here, only the second condition (marks >= 75) is true, so it prints “Grade B.”

Nested If Statements

When you put one if statement inside another, it’s called a nested if statement. It allows you to check multiple related conditions before deciding what to do.

Example:

int age = 20;
boolean hasID = true;

if (age >= 18) {
    if (hasID) {
        System.out.println("Access granted.");
    } else {
        System.out.println("You must show an ID.");
    }
} else {
    System.out.println("You are not old enough.");
}

In this case, both conditions must be true for access to be granted.

Using Logical Operators in If Conditions

You can use logical operators (&&, ||, !) to combine multiple conditions in a single if statement.

Example:

int temperature = 30;
boolean isSunny = true;

if (temperature > 25 && isSunny) {
    System.out.println("It's a great day for a picnic!");
}

Here, both conditions must be true for the message to display.

Short-Hand If...Else (Ternary Operator)

Java also provides a shorter way to write simple if...else statements, known as the ternary operator.

Syntax:

variable = (condition) ? valueIfTrue : valueIfFalse;

Example:

int age = 20;
String result = (age >= 18) ? "Adult" : "Minor";
System.out.println(result);

This is equivalent to:

if (age >= 18)
    result = "Adult";
else
    result = "Minor";

The ternary operator is ideal for quick decisions where you just want to assign a value based on a condition.

If...Else with User Input

In real-world programs, you’ll often use if...else statements to handle user input. For example:

import java.util.Scanner;

public class VotingCheck {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your age: ");
        int age = sc.nextInt();

        if (age >= 18) {
            System.out.println("You can vote.");
        } else {
            System.out.println("You cannot vote yet.");
        }
    }
}

This program asks for the user’s age and checks their eligibility to vote using an if...else condition.

Real-Life Use of If...Else in Programs

If...else statements are used in countless real-world scenarios. Here are a few examples:

  • Checking login credentials in a login form

  • Determining if a user has enough balance for a transaction

  • Validating form inputs

  • Controlling access to restricted areas

  • Changing behavior based on user choices

For instance, an e-commerce website uses if...else to check whether a coupon is valid or expired before applying a discount.

Summary of the Tutorial

The if...else structure is one of the most fundamental parts of programming logic in Java. It helps programs make decisions, control flow, and respond differently to various inputs. From basic conditions to complex nested checks, mastering if...else logic is key to becoming a confident Java developer.

With practice, you’ll use it naturally to write smart, interactive programs that respond to real-world conditions efficiently.


Practice Questions

  1. Write a Java program that takes a number as input and checks whether it is positive, negative, or zero using if...else statements.

  2. Create a Java program that accepts a user’s age and prints whether the person is a minor, an adult, or a senior citizen based on age ranges using if...else if...else.

  3. Write a program that asks the user to enter their marks and displays the grade (A, B, C, or Fail) using multiple if...else conditions.

  4. Develop a Java program that checks whether an entered year is a leap year or not using nested if statements.

  5. Write a program that takes two numbers and prints which one is greater, or prints “Both are equal” if they are the same.

  6. Create a Java program that asks the user for a username and password, and grants or denies access using if...else logic.

  7. Write a Java program that checks whether a character entered by the user is a vowel or consonant using an if...else structure.

  8. Develop a program that reads a temperature value and prints messages such as “Cold Day,” “Moderate Day,” or “Hot Day” depending on the temperature range.

  9. Write a program that checks if a person is eligible to donate blood based on age and weight using logical operators inside if conditions.

  10. Create a Java program that accepts a number and checks whether it is divisible by both 3 and 5, only 3, only 5, or neither using if...else if...else statements.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top