An if else statement in Java is a conditional statement. Java uses conditions just like mathematics, allowing comparisons that yield Boolean results. So you can test inputs to see how they compare to a static set of values that you specify. Because the result is Boolean, there are only two possible results: 0 or 1; that is, false, or true. An if else java statement is structured in two basic ways. The first is a simple if then statement in Java. The second is if-then-else. Using the else statement as a secondary execution path gives this conditional control a lot of flexibility.What are IF ELSE Java Statements? - 1

If Statement Java Syntax

The if statement in Java uses the following syntax:

	If (condition) {
		//do this code
	}
If the condition returns a Boolean value of true, then the code inside the brackets is executed. If the value returns as false, the bracketed code is skipped. Consider this code fragment.

	int a = 20;
	if (a%2 == 0) {
		System.out.println(a + " is even.");
	}
	…
The output in the above code will be "20 is even." That is because the condition that was tested was what the remainder would be when the integer a is divided by 2. Using a Java if statement is a good way to check on what’s going on during debugging code. If your code isn’t responding properly, you can insert a condition that simply tells your code to print a confirmation if it is working as expected. In this way, you can narrow down where code is misbehaving.

Java Syntax for If Else Statements

The if else java syntax is as follows:

	if (condition) {
		//do this code
	} else {
		//do this code
	}
As you can see, by adding the else statement, you can create a second set of statements that trigger when the Boolean response is false. Let’s add an else statement to our original code fragment and nest it inside of a simple incrementing for loop.

	…
	for (int x = 1; x <=4; x++) {
		if (x%2 == 0) {
			System.out.println(x + "  is even.");
		} else {
			System.out.println(x + " is odd.");
		}
	}
You can see that x will start at 1 and enter the loop and be tested by the same conditional. Because the modulus returned when 1 is divided by 2 is not zero, a false Boolean is returned. That skips the initial if statement and triggers the else statement. So the output for this loop would be:

	1 is odd.
	2 is even.
	3 is odd.
	4 is even.
While this is fun, you may be wondering what the practicality of java if else statements are. In the real world, they have huge benefits because they rely solely on the Boolean values of true and false. A video game like Fortnight uses an if else statement to determine if a player hits another player based on if the shot lands in a determined hitbox. A password checker compares your input with a stored password, and if it matches, it lets you in. Else, it doesn’t and tells you that the passwords don’t match. So, even considering how versatile an if else java statement is, you can make it even more versatile by adding more conditions. This is called a nested if else java statement.

Nested If Else and Else If Java Statements

When you start to nest, or repeat Java if else statements, you create a chain of conditions that are each checked for a Boolean value. The syntax looks like this:

	if (condition) {
		//do this code
	} else if (condition) {
		//do this code
	} else if (condition) {
 		//do this code
	} else {
		//do this code
	}
You can repeat the Java else if statement for as long as you like, and the system will continue to test the input. It is important to note that as soon as a condition returns a true Boolean, then that bracketed section of code will execute and the program will leave the entire if else code section.

Nested If Java Statements

You can also nest if statements that don’t have an else condition. So the code is simply, if this is true, AND this is true do this. Look at the syntax here:

	if (condition) {
		if (condition) {
			if (condition) {
				//do this code
			}
		}
	}
You can see that the code checks three different conditions before the final bracketed code runs. We can use this to check if a number is prime or not. Look at the following pseudo code which checks an integer x using nested if statements.

	if (x  > 1) {
		if (x is odd) {
			if (x modulo (every integer from 2 to x-1) != 0) {
				// integer is prime
			}
		}
	}
This code runs three checks:
  • Is the integer greater than 1, because 1 is not prime?
  • Is the integer is odd, because only odd numbers above 2 are prime?
  • Can any other integer from 2 to one less than x can divide evenly into it?
If all three conditions are met, then the number is prime. To reinforce what you learned, we suggest you watch a video lesson from our Java Course

What is the if-else-if Ladder?

You've already learned the basics of if-else statements, but what if you need to check more than two conditions? No worries! Java has you covered with the if-else-if ladder. Let's explore how this works and why it's so useful.

Imagine you're trying to figure out what to wear based on the weather. A simple if-else won't cut it, right? That's where the if-else-if ladder shines!

The if-else-if ladder allows you to check multiple conditions in sequence. Java evaluates each condition one by one, and as soon as it finds a condition that’s true, it executes that block of code and skips the rest. Pretty efficient, right?

Syntax of the if-else-if Ladder

if (condition1) {
    // Executes if condition1 is true
} else if (condition2) {
    // Executes if condition2 is true
} else if (condition3) {
    // Executes if condition3 is true
} else {
    // Executes if none of the above conditions are true
}

Practical Example of the if-else-if Ladder

Let’s say we want to print a message based on the temperature. Check this out!

public class WeatherAdvisor {
    public static void main(String[] args) {
        int temperature = 15;

        if (temperature >= 30) {
            System.out.println("It's a hot day! Stay hydrated.");
        } else if (temperature >= 20) {
            System.out.println("It's a warm day! Enjoy the sun.");
        } else if (temperature >= 10) {
            System.out.println("It's a bit chilly. Wear a jacket!");
        } else {
            System.out.println("Brrr... It's cold! Bundle up.");
        }
    }
}

Output:


It's a bit chilly. Wear a jacket!

Nice and simple! The program checks each condition in order and prints the message that matches the temperature. Easy, right?

Advantages of Using the if-else-if Ladder

So why should you use the if-else-if ladder? Let’s break it down.

  • **Simple and Readable:** Great for checking multiple conditions in a clear, step-by-step manner.
  • **Efficient:** Once a condition is met, the rest are skipped—saving processing time.
  • **Flexible:** Easily handles a wide range of conditions without needing extra tools or structures.

Limitations of the if-else-if Ladder

But hey, it’s not perfect. Let’s be honest about the downsides.

  • **Not Ideal for Too Many Conditions:** If you have a LOT of conditions, the ladder can get messy and hard to read.
  • **Slower for Complex Conditions:** If many conditions need to be evaluated, it might not be the most efficient choice.
  • **Better Alternatives Exist:** Sometimes a switch statement or even polymorphism can handle the job better.

When Should You Use the if-else-if Ladder?

Good question!

The if-else-if ladder is best when:

  • You need to evaluate multiple non-equal conditions (ranges, specific checks).
  • Conditions are complex expressions that a switch can’t handle.
  • You need to check values like ranges, booleans, or method results.

But if you're just checking exact matches, a switch statement might be cleaner.

Quick Comparison: if-else-if Ladder vs. switch Statement

Feature if-else-if Ladder switch Statement
Condition Types Works with any condition (ranges, booleans, expressions) Best for fixed values (integers, strings, enums)
Readability Less readable with many conditions More readable with many cases
Performance Slower for many conditions Faster due to optimized jump tables