Java if…else

Let’s understand with an example :

 In a beer shop 🍾🍾  if the shop keeper has “Tubo beer”  then people can buy “Tuborg beer” to drink

 people  buy “kingfisher beer”

in this example, work depends on a condition 

There are various type of if  statement in java

  • if statement
  • if-else statement
  • if-else-if ladder statement

 if statement:

If statement tests the condition. It executes the if block if the condition is true.

1.     if(condition){  
2.     //code to be executed  
3.     }  

diagram of if statement:

if else statement in java (diagram)

Example of if statement:-

1.     public class IfExample {  
2.     public static void main(String[] args) {  
3.         //defining an 'age' variable  
4.         int age=20;  
5.         //checking the age  
6.         if(age>18){  
7.             System.out.print("Age is greater than 18");  
8.         }  
9.     }  
  Age is greater than 18

if-else statement:-

In java, if-else is a statement which is used to execute code on a specific condition it returns boolean true  or false

Syntax of if-else :

if (condition)
     //if the condition is true this code execute
       // if condition is false this code execute 

Example of if-else:-

1.     //A Java Program to demonstrate the use of if-else statement.  
2.     //It is a program of odd and even number.  
3.     public class IfElseExample {  
4.     public static void main(String[] args) {  
5.         //defining a variable  
6.         int number=13;  
7.         //Check if the number is divisible by 2 or not  
8.         if(number%2==0){  
9.             System.out.println("even number");  
10.     }else{  
11.         System.out.println("odd number");  
12.     }  
 odd number

diagram of if-else:

if else statement in java

if-else-if ladder statement:

In this, we can execute many statement on different condition

In this, if statement is executed from top to down.

If one of the conditions is true the statement associated with that if execute, and the rest of the ladder is bypassed. If none of the condition is true then the final else statement will be executed

Syntax :

if (expression1)
   // codes
else if(expression2)
   // codes
else if (expression3)
   // codes
   // codes

Diagram of if-else-if

Java if-else-if ladder with Examples - flow chart


class Ladder {
   public static void main(String[] args) {  
      int number = 0;  
      if (number > 0) {
         System.out.println("Number is positive.");
      else if (number < 0) {
         System.out.println("Number is negative.");
      else {
         System.out.println("Number is 0.");
Number is 0.


Important Link