1.逻辑与(&&):
true&&true=true
true&&false=false
false&&true=false
false&&false=false
由上可以得出,只要有一个false,则可以肯定结果肯定为false。
短路特性:
public class Test
{
public static void main(String[] args)
{
int a = 1;
int b = 2;
int c = 3;
int d = 4;
boolean e = (a>b)&&((c=a)<4);
System.out.println(e);
System.out.println(c);
}
}
运行后结果:e=false c=3 ,我们看到 c 的值没有发生变化
分析:boolean e = (a>b)&&((c=a)<4); a>b为false,当程序运行到a>b时发现为false,程序可以肯定这结果为false,所以程序对于后面的((c=a)<4)不做出来,故有e=false c=3
2.逻辑或(||)
true||true=true
true||false=true
false||true=true
false||false=false
由上可以看出,只要有一个true,其结果必然为true。
短路特性:
public class Test
{
public static void main(String[] args)
{
int a = 1;
int b = 2;
int c = 3;
int d = 4;
boolean e = (a<b)||((c=a)<4);
System.out.println(e);
System.out.println(c);
}
}
运行结果:e=true c=3 ,c 的值仍然为 3.
这就是逻辑或的短路特性导致的