Java If和Else If之间的区别?

Java If和Else If之间的区别?,java,if-statement,Java,If Statement,我想知道为什么要使用else if语句,而不是多个if语句?例如,这样做的区别是什么: if(i == 0) ... else if(i == 1) ... else if(i == 2) ... 这是: if(i == 0) ... if(i == 1) ... if(i == 2) ... 它们似乎做了完全相同的事情。不同之处在于,如果第一个if为真,则所有其他if将不会执行,即使它们的计算结果为真。但是,如果它们是单独的Ifs,那么如果它们的计算结果为true,则所有Ifs将被执行。I

我想知道为什么要使用
else if
语句,而不是多个
if
语句?例如,这样做的区别是什么:

if(i == 0) ...
else if(i == 1) ...
else if(i == 2) ...
这是:

if(i == 0) ...
if(i == 1) ...
if(i == 2) ...

它们似乎做了完全相同的事情。

不同之处在于,如果第一个
if
为真,则所有其他
if
将不会执行,即使它们的计算结果为真。但是,如果它们是单独的
If
s,那么如果它们的计算结果为true,则所有
If
s将被执行。

If
语句检查所有可用的
If
。 而
else if
if
语句失败时检查,
if
语句返回true,则在
if
时不检查
else


因此,这取决于您的需求情况。

第一个示例不一定要运行3个测试,而第二个示例将不返回或返回

在第一种情况下,只要
if
else if
条件变为true,所有“else if”都将被跳过/不检查

if(i == 0) ... //if i = 0 this will work and skip the following else-if statements
else if(i == 1) ...//if i not equal to 0 and if i = 1 this will work and skip the following else-if statement
else if(i == 2) ...// if i not equal to 0 or 1 and if i = 2 the statement will execute


if(i == 0) ...//if i = 0 this will work and check the following conditions also
if(i == 1) ...//regardless of the i == 0 check, this if condition is checked
if(i == 2) ...//regardless of the i == 0 and i == 1 check, this if condition is checked
在第二种情况下,即使i的值为0,也会测试以下所有条件

因此,您可以推断,如果您测试的是同一个变量-在给定时间内不能有多个值,更好的选择是使用第一种方法,因为它将是最佳的。

不,它们是不同的。 执行将检查每个if。 i、 e

而if和else if

if(true)
 executes
else if(true)
 // system doesn't checks for this once if gets true

简而言之,将只执行任何其他if梯形图中的一个。

如果使用了多个
if
语句,则如果条件为
true
则将执行所有语句。如果使用了
If
else If
组合,则只有一个组合会在第一个值为真时执行

// if condition true then all will be executed
if(condition) {
    System.out.println("First if executed");
}

if(condition) {
    System.out.println("Second if executed");
}

if(condition) {
    System.out.println("Third if executed");
}


// only one will be executed 

if(condition) {
   System.out.println("First if else executed");
}

else if(condition) {
   System.out.println("Second if else executed");
}

else if(condition) {
  System.out.println("Third if else executed");
}

对于第一种情况:一旦else if(或第一个if)成功,剩余的else ifelse将不进行测试。但是,在第二种情况下,即使所有(或其中一个)都成功,也将测试每个if

请参见,如果要检查所有条件,如1、2、3。。。您可以选择第二个选项,但在许多情况下,您只能检查一个条件,因此您必须防止其他条件不执行,在特定情况下,您必须选择第一个选项,如果:仅在“条件”为真时执行


elif:只有当“条件”为假而“其他条件”为真时才执行

我知道它们不同,只是不确定确切的区别是什么。谢谢如果语句。。。
// if condition true then all will be executed
if(condition) {
    System.out.println("First if executed");
}

if(condition) {
    System.out.println("Second if executed");
}

if(condition) {
    System.out.println("Third if executed");
}


// only one will be executed 

if(condition) {
   System.out.println("First if else executed");
}

else if(condition) {
   System.out.println("Second if else executed");
}

else if(condition) {
  System.out.println("Third if else executed");
}