Question

If I have a statement block like this:

if (/*condition here*/){ }
else{ }

or like this:

if (/*condition here*/)
else if (/*condition here*/) {}
else if (/*condition here*/) {}

What is the difference?

It seems that with if/else, if part is for true state and the else part is for all other possible options (false). An else-if would be useful for a number of conditions. This is my understanding, is there anything more I should be aware of?

Was it helpful?

Solution

Situation a:

if( condition )
{
}
else
{
}

When the condition in the above statement is false, then the statements in the else block will always be executed.

Situation b:

if( condition )
{
}
else if( condition2 )
{
}
else
{
}

When 'condition' is false, then the statements in the else if block will only be executed when condition2 is true. The statements in the else block will be executed when condition2 is false.

OTHER TIPS

Without "elseif" syntax you would have to write chain if-statements for processing one of several possible outcomes this way:

if( str == "string1" ) {
   //handle first case
} else {
    if( str == "string2" ) {
       //handle second case
    } else {
       if( str == "string3" ) {
           //handle third case
       } else {
          //default case
       }
    }
 }

instead you can write

if( str == "string1" ) {
   //handle first case
} else if( str == "string2" ) {
   //handle second case
} else if( str == "string3" ) {
   //handle third case
} else {
   //default case
}

which is completely the same as the previous one, but looks much nicer and is much easier to read.

Many languages have a grammer like this (here: ECMAScript Language Specification, so JavaScript):

IfStatement :
    if ( Expression ) Statement else Statement
    if ( Expression ) Statement

Statement :
    Block
    VariableStatement
    EmptyStatement
    ExpressionStatement
    IfStatement
    IterationStatement
    ContinueStatement
    BreakStatement
    ReturnStatement
    WithStatement
    LabelledStatement
    SwitchStatement
    ThrowStatement
    TryStatement

Block :
    { StatementListopt }

StatementList :
    Statement
    StatementList Statement

So the branches of an ifStatement may contain a block of statements (Block) or one of the other statements (other than Block). That means this is valid:

if (expr)
    someStatement;
else
    otherStatement;

And as StatementList may just contain a single statement, these examples are equivalent to the previous:

if (expr) {
    someStatement;
} else {
    otherStatement;
}

if (expr)
    someStatement;
else {
    otherStatement;
}

if (expr) {
    someStatement;
} else
    otherStatement;

And when we replace otherStatement by an additional IfStatement, we get this:

if (expr) {
    someStatement;
} else
    if (expr) {
        someOtherStatement;
    }

The rest is just code formatting:

if (expr) {
    someStatement;
} else if (expr) {
    someOtherStatement;
}

Emphasizing what Gumbo said.

Also, if a language has a real elif / elsif / elseif (say, a "real" else-if instruction, instead of a kind of nested chaining hidden away by formatting), then the compiler can easly emit a single node in an Abstract Syntax Tree (or similar, see http://en.wikipedia.org/wiki/Abstract_syntax_tree) instead of nesting them.

To give an example:

Say in C/C++ you have:

if (a) {
    X
} else if (b) {
    Y
} else if (c) {
    Z
} else {
    0
}

Then the compiler will build an AST-node like this:

   a
  / \
 X   b
    / \
   Y   c
      / \
     Z   0

But if the language of choice has a real if-else:

if (a) {
    X
} elif (b) {
    Y
} elif (c) {
    Z
} else {
    0
}

Then the AST could more easily look like this:

   (a--b--c)
   /  /  /  \
  X  Y  Z    0

In such a language, an "if else" would only be possible if braces are not mandatory:

if (a) {
    X
} elif (b) {
    Y
} else if (c) {  // syntax error "missing braces" if braces mandatory
    Z
} else {
    0
}

Corresponding AST (if braces are not mandatory):

   (a--b)
   /  /  \
  X  Y    c
         / \
        Z   0

This could make CFG-Analysis (http://en.wikipedia.org/wiki/Control_flow_graph) easier to implement (though there might be no actual optimization benefit; so imho it'd just benefit the lazy programmer :D).

else if basically means the else part of if is another if statement.

**if/else**
if(condition)
  statement;
else
   statement;

if/ else if /else

if(condition)
 {
   if(condition)
      statement;
   else 
     statement;
  }   
else if(condition)
{
    if(condition)
     statement;
    else
     statement;
}
else
    statement;

if/else and if/else if used also like this

Given a single variable, you will use the simple if-else structure. When there are multiple variables and you have a different path to execute for the different possibilities, you will use if-else if-...-else. Note, that the latter also ends with an else statement.

You already gave the answer yourself. if/else is for true/false result, like is an int=2 or any other possible int value, and if/elseif is for more than 2 results, like an int=2, and int=3 and so on.

Also it groups the context of a variable. You could check every single result like

if (a == 2) { do one thing };
if (a == 3) { do another thing };
...
if (a != 2 && a != 3 ...) { do something else };

With if/else/elseif it's better readable.

if you want to check more condition we can use if..elseif. single condition then we can use if or if...else.

Here I can't able to upload the full explanation with example so please go through the following links.

if..else statement details
http://allinworld99.blogspot.in/2016/02/ifelse-flow-chart-with-easy-example.html
if...elseif details
http://allinworld99.blogspot.in/2016/02/flow-chart-with-example-for-if-then.html

import java.util.*;

public class JavaApplication21 {
    public static void main(String[] args) {

        Scanner obj = new Scanner(System.in);
        System.out.println("You are watching an example of if & else if statements");

        int choice, a, b, c, d;
        System.out.println(" Enter 1-Addition & 2-Substraction");

        int option = obj.nextInt();
        switch (option) {
            case (1):
                System.out.println("how many numbers you want to add.... it can add up to 3 numbers only");
                choice = obj.nextInt();
                if (choice == 2) {
                    System.out.println("Enter 1st number");
                    a = obj.nextInt();

                    System.out.println("Enter 2nd number");
                    b = obj.nextInt();

                    c = a + b;

                    System.out.println("Answer of adding " + a + " & " + b + " is= " + c);
                } else if (choice == 3) {
                    System.out.println("Enter 1st number");
                    a = obj.nextInt();

                    System.out.println("Enter 2nd number");
                    b = obj.nextInt();

                    System.out.println("Enter 3rd number");
                    c = obj.nextInt();

                    d = a + b + c;

                    System.out.println("Answer of adding " + a + " , " + b + " & " + c + "  is= " + d);
                }
            case (2):
                System.out.println("how many numbers you want to substract.... it can substract up to 3 numbers only");
                choice = obj.nextInt();
                if (choice == 2) {
                    System.out.println("Enter 1st number");
                    a = obj.nextInt();

                    System.out.println("Enter 2nd number");
                    b = obj.nextInt();

                    c = a - b;
                    System.out.println("Answer of substracting " + a + " & " + b + " is= " + c);
                } else if (choice == 3) {
                    System.out.println("Enter 1st number");
                    a = obj.nextInt();

                    System.out.println("Enter 2nd number");
                    b = obj.nextInt();

                    System.out.println("Enter 3rd number");
                    c = obj.nextInt();

                    d = a - b - c;
                    System.out.println("Answer of substracting " + a + " , " + b + " & " + c + "  is= " + d);
                }
            default:
                System.out.println("no option you have chosen" + option);
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top