If Else Statements in Java

In this tutorial we are going to learn about if, if else and else if statements in java followed by a few handy examples.


In programming,  it is highly expected to run a section of code that is based on a certain condition, that condition could be true or either false. For these programs, we use control flow statements. 

If statement tells us that if a certain condition is true it will execute a set of statements and if it’s false then there would be no execution,  but let’s say that we want to do something if the condition becomes false and we want to proceed onwards.  Then,  we will use the if else statement to execute the if conditions more than once.

Recommended Books



The If Condition in Java

In Java the syntax of if statement look like below:

If (expression)  {
// statements
}

Here the expression is a Boolean expression and the Boolean expression can return true or false. Let’s look at how a conditional block looks like:





In the above picture you can see,  that the moment the code block runs a certain condition is passed on and if that condition turns are to be true then the conditional code gets executed,  what if the condition becomes false then the program just ends.

Example 1:

public class ifdemo {

   public static void main(String args[]) {
      int x = 30;

      if( x < 20 ) {
         System.out.print("Statement is True");
      }
      
     System.out.print("Condition didn't meet");
     
   }
}

Output

Condition didn't meet

The If-Else Statement in Java

However in the if else statement if the condition does not meet the criteria of both true or false conditions then the else code gets executed.

Example 2:

public class IfElse {

   public static void main(String args[]) {
      int x = 20;

      if( x == 10 ) {
         System.out.print("Value of X is 10");
      }
      
      else {
         System.out.print("This is else statement");
      }
   }
}

Output

This is else statement

The Else-If Statement in Java

Example 3:

public class IfElse_ElseIf {

   public static void main(String args[]) {
      int x = 20;

      if( x == 10 ) {
         System.out.print("X is 10");
      }else if( x == 30 ) {
         System.out.print("X is 30");
      }else {
         System.out.print("This is else statement");
      }
   }
}

Output:

This is else statement