Java If ... Else


Conditions

Java thus supports the logical conditions of arithmetic. In the following example, 'a' and 'b' are taken as two numbers -


The if statement

If any condition is placed inside the '()' in the first bracket of the 'if' statement in Java. So if that condition is true then the 'if' block will work or the 'else' block will work.

Program
public class Main
{
   public static void main(String[] args) 
   {
      int a = 10, b=10;
      if(a == b)
      {
	System.out.println("Yes, this condition is true");
      }
    }
}
Run

In the above example, the code of the block of the 'if' statement is working as 'a = 10' and 'b = 10' are equal.


The else statement

If any condition is placed inside the '()' in the first bracket of the 'if' statement in Java. So if that condition is false then the 'else' block will work.

Program
public class Main
{
   public static void main(String[] args) 
   {  		
     int a = 10, b=11;
     if(a == b)
     {
	System.out.println("Yes, this condition is true");
     }
     else
     {
        System.out.println("No, this condition is false");
     }
   }
}
Run

In the above example the code of the statement 'else' has worked because the values of 'a = 10' and 'b = 11' are not equal


The else..if statement

If the first condition is false, use the 'else if' statement to specify the new condition.

Program
public class Main
{
   public static void main(String[] args) {
    int a = 10, b=13, c=12;
    if(a > b && a > c)
    {
       System.out.println("a is big number");
    }
    else
    {
       if(b > c)
       {
          System.out.println("b is big number");
       }
       else
       {
          System.out.println("c is big number");
       }
     }
  }
}
Run

In the example above, the first condition is false and the output 'b is big number' is printed as the 'else if' condition is true.


The nested if statement

If the first 'if' condition is true then the nested 'if' statement will be checked again.

Program
public class Main
{
   public static void main(String[] args) {
     int a = 10, b=13, c=12;
	if(a > b)
	{
	    if(a > c)
	    {
	       System.out.println("a is big number");
	    }
	}
	else
	{
	    if(b > c)
	    {
	       System.out.println("b is big number");
	    }
	    else
	    {
	        System.out.println("c is big number");
	    }
	}
   }
}
Run

The 'else if' statement is working to make the nested 'if' statements false in the example above.