链接if构造在Java中做了什么?

Ros*_*oss -1 java if-statement chained

通过阅读Oracle iLearning Java课程,我的印象是使用'chained if construct'相当于使用'&&'运算符.所以:

 if((5 < 10) && (5 < 6)) {
    run some code;
}
Run Code Online (Sandbox Code Playgroud)

是相同的:

if(5 < 10) {
  if(5 < 6) {
        run some code;
    }
}
Run Code Online (Sandbox Code Playgroud)

比较两者,我觉得很难相信.我想我很误解.

GBl*_*ett 5

我们可以将此代码重写为:

if(someCondition)` {
    if(otherCondition) {
        //code
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,无论someConditionotherCondition对必须是真实的//code来运行.(关键词AND).所以在这个例子if(someCondition && otherCondition)中等同于上面的代码


通常你会使用嵌套的原因if是你想要检查多个条件,例如:

if(someCondition) {
   if(otherCondition1) {
      //code
   }
   else if(otherCondition2) {
     //code
   } else {
     //else
   }
}
Run Code Online (Sandbox Code Playgroud)