Java If-Else Control Statement with Program Examples

In this tutorial post we will study and understand the working of the Java If-Else Conditional Statements.

  • if statement
  • if-else statement
  • if-else-if ladder
  • nested if statement
Java if Statement

The Java if statement tests the condition. It executes the if block if condition is true.

java if block flow diagram
Syntax:
if(condition){  
//code to be executed  
}
Program Example –
public class IfExample {  
public static void main(String[] args) {  
    int num=20;  
    if(num>0){  
        System.out.print("Positive");  
    }  
}  
}
Output
Positive
Java if-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else block is executed.
java if else block flow diagram
Syntax:
if(condition){  
//code if condition is true  
}else{  
//code if condition is false  
}
Program Example –
public class IfElseExample {  
public static void main(String[] args) {  
    int number=13;  
    if(number%2==0){  
        System.out.println("even number");  
    }else{  
        System.out.println("odd number");  
    }  
}  
}
Output
odd number
Java if-else-if ladder Statement

The if-else-if ladder statement executes one condition from multiple statements. It is used when more than 1 condition is to be checked in relation with the problem.

Java if-else-if ladder Statement

Syntax:
if(condition1){  
//code to be executed if condition1 is true  
}else if(condition2){  
//code to be executed if condition2 is true  
}  
else if(condition3){  
//code to be executed if condition3 is true  
}  
...  
else{  
//code to be executed if all the conditions are false  
}
Program Example –
public class IfElseIfExample {  
public static void main(String[] args) {  
    int num=0;  
      
    if(num<0){  
        System.out.println("Negative");  
    }  
    else if(num>0){  
        System.out.println("Positive");  
    }  
    }else{  
        System.out.println("Neither Negative nor Positive");  
    }  
}  
}
Output
Neither Negative nor Positive
Watch it on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *