DEV Community

Neelakandan R
Neelakandan R

Posted on

Java if-else Statement

You already know that Java supports the usual logical conditions from mathematics:(TBD)
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.

Java has the following conditional statements:

Use if to specify a block of code to be executed, if a specified condition is true

Use else to specify a block of code to be executed, if the same condition is false

Use else if to specify a new condition to test, if the first condition is false

Use switch to specify many alternative blocks of code to be executed(TBD)

How Does It Work?

When the 'if-else' statement is encountered, the condition within the parentheses is evaluated. If the condition evaluates to true, the block of code inside the 'if' block is executed. However, if the condition evaluates to false, the block of code inside the 'else' block is executed. It allows the program to take different paths based on the outcome of the condition.

The if Statement

Use the if statement to specify a block of Java code to be executed if a condition is true.

Syntax

if (condition) {
  // block of code to be executed if the condition is true
}
Enter fullscreen mode Exit fullscreen mode

Image description

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.

if (20 > 18) {
  System.out.println("20 is greater than 18");

Enter fullscreen mode Exit fullscreen mode

}

OUTPUT:

20 is greater than 18

The else Statement

Use the else statement to specify a block of code to be executed if the condition is false.

Syntax

if (condition) {
  // block of code to be executed if the condition is true
} else {
  // block of code to be executed if the condition is false
}

Enter fullscreen mode Exit fullscreen mode

Example

int time = 20;
if (time < 18) {
  System.out.println("Good day.");
} else {
  System.out.println("Good evening.");
}

Enter fullscreen mode Exit fullscreen mode

*Outputs *
"Good evening."

The else if Statement

Use the else if statement to specify a new condition if the first condition is false.

Syntax

if (condition1) {
  // block of code to be executed if condition1 is true
} else if (condition2) {
  // block of code to be executed if the condition1 is false and condition2 is true
} else {
  // block of code to be executed if the condition1 is false and condition2 is false
}
Enter fullscreen mode Exit fullscreen mode

Image description

Example

int time = 22;
if (time < 10) {
  System.out.println("Good morning.");
} else if (time < 18) {
  System.out.println("Good day.");
} else {
  System.out.println("Good evening.");
}

Enter fullscreen mode Exit fullscreen mode

Outputs
"Good evening."

Java if-else-if ladder Statement

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

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  
    }  
Enter fullscreen mode Exit fullscreen mode

Image description

** Example**: 1

  public class IfElseIfExample {  
    public static void main(String[] args) {  
        int marks=65;  

        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!");  
        }  
    }  
    }  
Enter fullscreen mode Exit fullscreen mode


Output:

C grade

Example 2

 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");  
       }  
    }    
    }  
Enter fullscreen mode Exit fullscreen mode

Output:

NEGATIVE

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.

Syntax:

 if(condition){    
         //code to be executed    
              if(condition){  
                 //code to be executed    
        }    
    }  
Enter fullscreen mode Exit fullscreen mode

Image description


    Java Program to demonstrate the use of Nested If Statement.  
    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");  
            }    
        }    
    }}  

Enter fullscreen mode Exit fullscreen mode

Output:

You are eligible to donate blood

Example 2:

  //Java Program to demonstrate the use of Nested If Statement.    
    public class JavaNestedIfExample2 {      
    public static void main(String[] args) {      
        //Creating two variables for age and weight    
        int age=25;    
        int weight=48;      
        //applying condition on age and weight    
        if(age>=18){      
            if(weight>50){    
                System.out.println("You are eligible to donate blood");    
            } else{  
                System.out.println("You are not eligible to donate blood");    
            }  
        } else{  
          System.out.println("Age must be greater than 18");  
        }  
    }  }  

Enter fullscreen mode Exit fullscreen mode

Output:

You are not eligible to donate blood

Short Hand if...else(TBD)

There is also a short-hand if else, which is known as the ternary operator because it consists of three operands.

Ternary Operator

We can also use ternary operator (? :) to perform the task of if...else statement.

It can be used to replace multiple lines of code with a single line, and is most often used to replace simple if else statements:

Syntax


variable = (condition) ? expressionTrue :  expressionFalse;

Enter fullscreen mode Exit fullscreen mode

Instead of writing:
Example

int time = 20;
if (time < 18) {
  System.out.println("Good day.");
} else {
  System.out.println("Good evening.");
}
Enter fullscreen mode Exit fullscreen mode

You can simply write:
Example

int time = 20;
String result = (time < 18) ? "Good day." : "Good evening.";
System.out.println(result);

Reference:https://www.w3schools.com/java/java_conditions_elseif.asp

Reference:https://www.javatpoint.com/java-if-else

Reference:https://www.geeksforgeeks.org/java-if-else-statement-with-examples/

Top comments (1)

Collapse
 
payilagam_135383b867ea296 profile image
Payilagam

Good Effort!