Are multiple 'if' statements and 'if-else-if' statements the same for mutually exclusive conditions?

梦想与她 提交于 2019-12-09 17:05:08

问题


Is there any difference between writing multiple if statements and if-else-if statements ?

When I tried to write a program with multiple if statements, It did not give the expected results, But it worked with if-else-if.

The conditions were mutually exclusive.


回答1:


When you write multiple if statements, it's possible that more than one of them will be evaluated to true, since the statements are independent of each other.

When you write a single if else-if else-if ... else statement, only one condition can be evaluated to true (once the first condition that evaluates to true is found, the next else-if conditions are skipped).

You can make multiple if statements behave like a single if else-if .. else statement if each of the condition blocks breaks out of the block that contains the if statements (for example, by returning from the method or breaking from a loop).

For example :

public void foo (int x)
{
    if (x>5) {
        ...
        return;
    }
    if (x>7) {
        ...
        return;
    }
}

Will have the same behavior as :

public void foo (int x)
{
    if (x>5) {
        ...
    }
    else if (x>7) {
        ...
    }
}

But without the return statements it will have different behavior when x>5 and x>7 are both true.




回答2:


No both are not same. if statements will check all the conditions. If you will write multiple if statement it will check every condition. If else will check conditions until it is satisfied. Once if/else if is satisfied it will be out of that block.




回答3:


Yes, it makes a difference: see The if-then and if-then-else Statements.

Furthermore, you can easily test it.

Code #1:

    int someValue = 10;

    if(someValue > 0){
        System.out.println("someValue > 0");
    }

    if(someValue > 5){
        System.out.println("someValue > 5");
    }

Will output:

someValue > 0
someValue > 5

While code #2:

    int someValue = 10;

    if(someValue > 0){
        System.out.println("someValue > 0");
    }else if(someValue > 5){
        System.out.println("someValue > 5");
    }

Will only output:

someValue > 0

As you can see, code #2 never goes to the second block, as the first statement (someValue > 0) evaluates to true.




回答4:


if()
{
stmt..
}
else
{
stmt
}
if()
{
stmt
}
here compiler will check for both the if condition.

In below fragement of code compiler will check the if conditions, as soon as first if condition get true remaining if condition will be bypass.

        if(){

        }
        else if
        {

        }
        else if
        {

        }
        else if
        {

        }


来源:https://stackoverflow.com/questions/29945412/are-multiple-if-statements-and-if-else-if-statements-the-same-for-mutually-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!