Java Selection Statements: if-else Statements
As we have seen, an if statement on its own will execute a code block if a certain condition is true and it will ignore the code block if the condition is false. Pretty simple and straight forward.
But what if we want to do something else if the condition is false? Rather than simply exit the if statement altogether it might be useful to execute an another code block. This is exactly what an else statement does. We can use the else statement with if statement to execute a block of code when the condition is false. The General syntax is:
if (condition) {
// Executes this block if
// condition is true
// also known as the true condition
} else {
// Executes this block if
// condition is false
// also known as the false condition
}
Let’s see how this might work in practice. Let’s write some code that checks the balance of a bank account before a withdrawal is made. If the amount the user wishes to withdraw is larger than the amount in the account the program must decline the request. But if there are sufficient funds in the account the program should allow the withdrawal and display the new balance to the user:
int accountBalance = 100; int withdrawalAmount = 50; if(withdrawalAmount > accountBalance) { System.out.println("Insufficient Funds."); System.out.println("Choose an amount less than " + accountBalance); } else { System.out.println("Withdrawal Successful."); accountBalance = accountBalance - withdrawalAmount; System.out.println("Your New Balance: " + accountBalance); }
When you run this code with an account balance of 100 and a withdrawal amount of 50 you should see that the transaction is allowed and the new balance is 100-50 = 50:
run: Withdrawal Successful. Your New Balance: 50 BUILD SUCCESSFUL (total time: 0 seconds)
Try changing the withdrawal amount so that it is large than the account balance. The program should prevent the user from withdrawing any money with a reminder of how much is left in their back account.
As you can see, the else statement is very useful and provides a mechanism to deal with an alternate outcome that can deliver useful information to users or adjust data as required when the if statement condition evaluates to false.