Java Else If Statement in Five Minutes

Share this article

Java Else If Statement in Five Minutes

Conditional statements, like the Java if else statement, are fundamental for imperative programming languages, including Java. The if else statement is used to instruct a program to act differently based on whether something is true or false. Java’s if statement is the most basic conditional statement – it evaluates a boolean expression and executes code based on its outcome.

To follow along, you need to understand equality, relational, and conditional operators and how to form boolean expressions with them. You should be good to go if you get why 1 > 0 evaluates to true and num == 5 evaluates to false when num equals anything other than 5.

The if Statement

The if statement or if then statement is the most fundamental control flow statement. Once you understand the if statement, the others will come easily. Essentially, an if statement tells a program to execute the following block of code only if the accompanying condition is true.

Here you can see the anatomy of an if statement:

int num = 5;

if (num == 5) {
    System.out.println("This message gets printed because num is 5.");
}

A variable num is declared and set to 5. What comes after that is the if statement.

The if statement starts with the keyword if followed by a pair of parenthesis. Between the parenthesis, you need to provide a condition. A condition is a boolean expression – something that evaluates to either true or false. It can be a variable of type boolean, equality, relational, or conditional expressions (like num == 5), or even a method call that returns a boolean. Boolean object wrappers are also valid.

After the parenthesis you can see a pair of curly braces defining a block of code, often called the if block or if branch. That code is only executed if the condition evaluated to true.

It is common practice to indent your if statement as it provides a visual hint for readers. For code blocks that contain only a single line of code you can omit the curly braces – whether you should is a different discussion.

The if else Statement

In many cases, you might want to do two different things based on whether a condition is true or not. This is commonly referred to as an if else statement, or if then else statement.

If a condition holds true, then execute the following block of commands, otherwise (else) execute a different block, often called the else block or else branch.

With the Java if else statement, you can optionally provide an alternative execution path that will be followed if the condition evaluates to false.

int num = 5;

if (num > 10) {
    // if branch
    System.out.println(
            "This will not be printed, since num is not greater than 10.");
} else {
    // else branch
    System.out.println(
            "This will be printed because the condition is false.");
}

This example is similar to the previous one – again num is declared and set to 5. But this time the boolean test is slightly different! Only if num is greater than 10, will the expression evaluate to true. Since this is not the case, the test evaluates to false. According to the if else statement rules we defined earlier, the following block of code cannot be executed. Instead, the program’s execution jumps directly to the else block to handle the false case.

The if-else-if Statement

Sometimes you might want to test against multiple boolean expressions, so a plain if else statement does not quite cut it. For example, if a condition holds true, then do something, else if another condition holds true, then do that another thing. You can of course nest a new if statement inside an else block, but nested conditional blocks get rather unreadable.

Instead, it is common practice in Java to pull the second if up into the same line as the else, thus chaining the statements together. This allows you to check against multiple conditions and pick the first block of code that passes its boolean test.

String callsign = "Maverick";

if ("Iceman".equals(callsign)) {
    System.out.println("You must be Lt. Tom Kazanski");
}
else if ("Maverick".equals(callsign)) {
    System.out.println("You must be Lt. Pete Mitchell");
}
else {
    System.out.println("I'm sorry, I believe we have not met");
}

In this example, we have a String variable callsign. The program first checks if it equals "Iceman". This obviously returns false, so the execution jumps into the first else where a new if waits. Then callsign is compared against "Maverick". This returns true and the following block of code is executed.

You can make use of the else statement to provide a default execution path, which will be executed if none of the conditions evaluated to true. In an if-else-if chain, only one block of code gets executed, and others are ignored.

If statements are junctions in your code

Summary

The if statement is the most basic conditional statement. It checks a condition, which is any boolean expression, and runs a block of code if it is true. The else keyword in a Java if else statement provides an alternative execution path that gets executed if the condition is false. To test multiple conditions you can chain if conditions with else if.

Although this article gave you an overview of the variations of if statements, it did not cover all the conditional statements available in Java. First of all, we did not talk about the ternary operator, which can be summarized as a shortcut for the if statement. Long else if chains can potentially be replaced with switch statements. And Sometimes it is even possible to avoid if statements altogether using dynamic dispatch.

Frequently Asked Questions (FAQs) about Java’s If Statement

How can I use multiple conditions in a Java if statement?

In Java, you can use multiple conditions in an if statement by using logical operators such as && (AND) and || (OR). For instance, if you want to check if a variable ‘a’ is greater than ‘b’ and ‘c’ is less than ‘d’, you can write it as:
if (a > b && c < d) {
// code to execute if both conditions are true
}
The code inside the if statement will only execute if both conditions are true. If you want the code to execute if either one of the conditions is true, you can use the OR operator:
if (a > b || c < d) {
// code to execute if either condition is true
}
The code inside the if statement will execute if either ‘a’ is greater than ‘b’ or ‘c’ is less than ‘d’.

What is the best way to format an if statement with multiple conditions?

Formatting an if statement with multiple conditions for readability is crucial. It’s best to use parentheses to group conditions and make the logic clear. For example:
if ((a > b && c < d) || (e > f && g < h)) {
// code to execute if conditions are true
}
In this example, the conditions ‘a > b’ and ‘c < d’ are grouped together, as are ‘e > f’ and ‘g < h’. This makes it clear that the AND operations are performed first, then the OR operation.

How do Java if-else and switch statements differ?

If-else and switch are both control flow statements in Java, but they are used in different scenarios. If-else is used when you want to choose between two or more blocks of code to execute based on a condition. Switch is used when you have a single variable that can take on multiple values and you want to execute different blocks of code based on its value.

Can I use OR conditions in a Java if statement?

Yes, you can use OR conditions in a Java if statement using the || operator. For example:
if (a > b || c < d) {
// code to execute if either condition is true
}
In this example, the code inside the if statement will execute if either ‘a’ is greater than ‘b’ or ‘c’ is less than ‘d’.

How can I use if-else statements in Java?

In Java, you can use if-else statements to execute different blocks of code based on a condition. For example:
if (a > b) {
// code to execute if 'a' is greater than 'b'
} else {
// code to execute if 'a' is not greater than 'b'
}
In this example, if ‘a’ is greater than ‘b’, the first block of code will execute. If ‘a’ is not greater than ‘b’, the second block of code (the else block) will execute.

Indrek OtsIndrek Ots
View Author

Software developer, hardware hacker, interested in machine learning, long distance runner.

control flownicolaipquick-tip
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week