In if statement the block of statements will be executed if the given condition is true otherwise block of the statement will be skipped. But we also want to execute some other block of code if the condition is false. In this type of scenario, we can use the if else statement in Java. There are two blocks one is if block and another is else block. If a certain condition is true, then if block will be executed otherwise else block will be executed.
Syntax

In Java, if statement having an optional block and this block is known as else block. You must think why we are saying else block is optional? Because if block can be used without else block but else block exists only with if block. The statements inside of else block will be executed only if the test expression is evaluated to false. There are a number of the situation when we want to execute the code based different situation. Suppose you want to perform TASK1 when code is satisfying the if condition otherwise you want to perform a different tasks.
RULE: You can place any code in between closing braces of if (‘}’) and else.
Flowchart of if-else statement

class ExampleIfElseStatement { public static void main(String args[]) { int age = 15; if (age > 18) // if age is greater than 18 { // It will be print if block condition is true. System.out.println("The age of person is : " + age + "He/she is eligible for voting"); } else { // It will be print if block condition is false. System.out.println("He/she is not eligible for voting"); } } }
Output: He/she is not eligible for voting
In the above example, A person is eligible for a vote only if he/she is above 18 otherwise he/she is not eligible for voting. Here we want to show message to person whether he/she is able to vote or not? First of all, we need to check the age of the person.
So Here are using the if-else statement.
The if block condition is checking, Is the person is above 18 or not?
The else block executed only when the evaluation of the condition is false.
If a person is greater than 18 then if block is getting executed otherwise else block.
1. Quiz, Read the below code and do answer.
Click on anyone to know the answer.