Menu

Java If-else Statement

The Java if statement is used to test the condition. It checks boolean condition: true or false. There are various types of if statement in Java.

  • 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.

if(condition){  
//code to be executed  
}  

Example:

//Java Program to demonstate the use of if statement.  
public class IfExample {  
public static void main(String[] args) {  
    //defining an 'age' variable  
    int age=20;  
    //checking the age  
    if(age>18){  
        System.out.print("Age is greater than 18");  
    }  
}  
}  

The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else block is executed.

Example:

public class IfElseExample {  
public static void main(String[] args) {  
    //defining a variable  
    int number=13;  
    //Check if the number is divisible by 2 or not  
    if(number%2==0){  
        System.out.println("even number");  
    }else{  
        System.out.println("odd number");  
    }  
}  
}  

Using Ternary Operator

We can also use ternary operator (? 🙂 to perform the task of if…else statement. It is a shorthand way to check the condition. If the condition is true, the result of ? is returned. But, if the condition is false, the result of : is returned. Example:

public class IfElseTernaryExample {    
public static void main(String[] args) {    
    int number=13;    
    //Using ternary operator  
    String output=(number%2==0)?"even number":"odd number";    
    System.out.println(output);  
}    
}    

Java if-else-if ladder Statement

The if-else-if ladder statement executes one condition from multiple statements. Example:

public class PositiveNegativeExample {    
public static void main(String[] args) {    
    int number=-13;    
    if(number>0){  
    System.out.println("POSITIVE");  
    }else if(number<0){  
    System.out.println("NEGATIVE");  
    }else{  
    System.out.println("ZERO");  
   }  
}    
}    

Java Nested if statement

The nested if statement represents the if block within another if block. Here, the inner if block condition executes only when outer if block condition is true. Example:

public class JavaNestedIfExample {    
public static void main(String[] args) {    
    //Creating two variables for age and weight  
    int age=20;  
    int weight=80;    
    //applying condition on age and weight  
    if(age>=18){    
        if(weight>50){  
            System.out.println("You are eligible to donate blood");  
        }    
    }    
}}  

Leave a Reply

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