Java – If-Else
If Statement
When a condition is assessed as true, the If statement is used to run a block of code. The software will bypass the if-code block if the condition is found to be untrue.
Syntax
if(condition){ statements; }
Flow Diagram:
The if code block is generated in the example below, and it only runs when the variable “i” is divisible by three.
public class MyClass { public static void main(String[] args) { int i = 15; if (i % 3 == 0){ System.out.println(i+" is divisible by 3."); } } }
The output of the above code will be:
15 is divisible by 3.
If-else Statement
With an, if statement, the else statement is always utilised. When an if condition returns a false result, it is used to run a block of code.
Syntax
if(condition){ statements; } else { statements; }
Flow Diagram:
In the example below, else statement is used to print a message if the variable i is not divisible by 3.
public class MyClass { public static void main(String[] args) { int i = 16; if (i % 3 == 0) { System.out.println(i+" is divisible by 3."); } else { System.out.println(i+" is not divisible by 3."); } } }
The output of the above code will be:
16 is not divisible by 3.
else if Statement
The else if statement is used to add further criteria. The programme begins by examining the if condition. When a condition is discovered to be untrue, it evaluates other if conditions. If any of the other if conditions are discovered to be untrue, the else code block is run.
Syntax
if(condition){ statements; } else if(condition) { statements; } ... ... ... } else { statements; }
Flow Diagram:
In the example below, else if statement is used to add more conditions between if statement and else statement.
public class MyClass { public static void main(String[] args) { int i = 16; if (i > 25){ System.out.println(i+" is greater than 25."); } else if(i <=25 && i >=10){ System.out.println(i+" lies between 10 and 25."); } else { System.out.println(i+" is less than 10."); } } }
The output of the above code will be:
16 lies between 10 and 25.