Java uses if/else statement for conditional control flow. It is used to test the conditions and based on the Boolean result (true or false) of the condition the control of the execution is decided.
There are 4 ways to write an if-else statement:
- if statement
- if-else statement
- if-else if statement
- nested if statement
if statement
Java if statement tests the condition and executed only if the condition is true. It has only if block, no else block.
Syntax:
if(condition) // enter the condition in the parenthesis
{
// code to be executed when the condition is true.
}
Example:
public class example{
public static void main(String arg[]){
int n = 10;
if(n > 11){ // condition is false so the if block is not fired
System.out.println(“Number is greater”);
}
}
}
if-else Statement
Java if-else statement tests the condition where if block is fired when the condition is true, if not then the else block is executed.
Syntax:
if(condition){
//code to be executed when the condition is true
}
else{
//code to be executed when the condition is false
}
Example:
public class example{
public static void main(String arg[]){
int n = 10;
if( n % 2 == 0){ // condition to check if number is divisible by 2
System.out.println(“Number is even”);
}
else{
System.out.println(“Number is odd”);
}
}
}
if-else if Statement
Java if-else if ladder executes one block among multiple conditional blocks. This is used when there are different code to be executed based on the conditions.
Syntax:
if(condition1){
//code to be executed when the condition1 is true
}
else if(condition2){
//code to be executed when the condition2 is true
}
else if(condition3){
//code to be executed when the condition3 is true
}
…
else{
//code to be executed when all conditions are false
}
Example:
public class example{
public static void main(String arg[]){
int marks =55;
if( marks < 50){
System.out.println(“Fail”);
}
else if( marks >= 50 && marks < 60){
System.out.println(“D grade”);
}
else if( marks >= 60 && marks < 70){
System.out.println(“C grade”);
}
else if( marks >= 70 && marks < 80){
System.out.println(“B grade”);
}
else if( marks >= 80 && marks < 90){
System.out.println(“A grade”);
}
else if( marks >= 90 && marks < 100){
System.out.println(“A+ grade”);
}
else{
System.out.println(“Invalid”);
}
}
}
Nested if statement
Java nested if statement represents if block within another if block. Here, the inner if block is executed only if the outer if block condition is true.
Syntax:
if(condition){
// code to be executed
if(condition){
// code to be executed
}
}
If you like this article, please click on recommend and share it.