If statement with && where the first condition needs to be true before testing the second [duplicate]

不问归期 提交于 2019-12-10 18:30:00

问题


Sorry if this is a duplicate, but I can't even think of a way to search of this. I'm not sure of the terminology to ask the question, so I'll just walk through my problem.

From my tests, it seems the if statement will quit before attempting to go to go to array[10]. I that always the case? Meaning, if I have an && in my if statement and the left side is false, will it always exit before testing the second? And for that matter, will it always test the left first?

public static void main(String[] args) {
        boolean [] array = new boolean [10];
        Arrays.fill(array, true);
        int i = 10;
        if(i < array.length && array[i]){
            System.out.println("WhoHoo!");
        }
}

回答1:


From the Java Tutorials on operators:

The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.




回答2:


Yes. If the left side is false, it will terminate the condition. Because if you put && then all the conditions must be true, if anyone condition turns false, then there is no need to go further. So it terminates when the condition gets false




回答3:


if I have an && in my if statement and the left side is false, will it always exit before testing the second?

Yes. If the left side is false, there is no need to check the right side, because when you have:

if(a && b) { ... }

If !a, then the whole statement is evaluated to false no matter what b is.

If a, then it will continue to evaluate the next.

For summary, always remember this:

...the second operand is evaluated only if needed.




回答4:


It will only evaluate second condition if first condition evaluates to true.

The evaluation starts from left and when it evaluates to false further evaluation does not happen.



来源:https://stackoverflow.com/questions/16033085/if-statement-with-where-the-first-condition-needs-to-be-true-before-testing-t

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