Search⌘ K
AI Features

The if-else Statement

Explore how if-else statements enable decision-making in Java programs. Understand syntax, practical examples with data comparisons, and when to use else clauses or the ternary operator for clarity in your code.

What is an if-else statement?

So far, we have used the if statement to do something if a certain condition is true, but to not do it if the condition is false. Frequently, however, you want to do one thing if a certain condition is true and another thing if it is not, as the figure given below illustrates.

In these situations, an if statement can have an else clause that indicates what to do when the condition is false. This kind of if statement is sometimes called an if-else statement. It has the following form:

📝 Syntax: The if-else statement

if ( condition )
   statement1
else  
   statement2  
}

Effect: statement1 executes only if condition is true; statement2 executes only if condition is false.

Example 1

A portion of a bank’s program that maintains our checking account could use BigDecimal objects to represent monetary values, as we saw in an earlier chapter. Suppose that balance and checkAmount are variables whose type is BigDecimal ...