Java : if-else-if Statement


The if-else-if statement is the decision-making statement, Use If the if-statement conditional statement execution result is false then control will reach to check conditions for an else-if statement. If the result is true, block associated with else-if statement will execute otherwise control will reach to else block. We can add multiple else-if statements consecutively.

Syntax:

if(test_expression)
{
   //execute your code
}
else if(test_expression n)
{
   //execute your code
}
else
{
   //execute your code
}

Note :
An if-else-if statement else is an optional clause. Below is the format without the else clause:

if (test-expression)
{
statement
}
else if (test-expression)
{
statement
}

See Also :

if-else-if Statement Example

public class IfStatementTest{

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

      if(a>0){
         System.out.println("a is positive number");
      }
	  if(a<0){
         System.out.println("a is negative number");
      }
	  else{
         System.out.println("a is zero");
      }
}

Output


a is positive number

Note :
The if-else-if statement can be a simple statement terminated by a semicolon or a block enclosed in curly braces.
For Example, the Below code is equivalent to the same as the above example and returns the same result.

public class IfElseIf{

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

      if(a>0)
         System.out.println("a is positive number");
      else if(a<0)
         System.out.println("a is negative number or zero");
      else
         System.out.println("a is zero");

}

Recommendation :

  • For a better understanding of code always use curly braces ({}) with if, if-else-if or if-else statements.
  • It always creates confusion when more than one statement is in code.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s