这四个操作符的区别可以通过名字容易的区分: ||(短路或),|(或),&&(短路与),&(按位与) 通过一个简单的例子讲解一下:
这个程序输出的i值是 0 原因是||在判断的时候,如果前面判断已经为true,那么就不会再判断后面的语句是否为真,那么后面的语句就不会执行。
如果将||换成|,结果会是怎样的呢
结果输出i的值是1, 原因是|操作符在进行判断的时候,无论前面的表达式是否为真,都会去执行后面的语句,那么,i的值就会加1,变成1。
结果输出i的值是1 原因是&&操作符在进行判断的时候,当第一个表达式为false的时候,就会直接判断整个表达式为false,就不会执行后面的语句了。
将&&换成&
1
2
3
4
5
6
7
8
9
10
|
public
class
Test1 {
public
static
void
main(String[] args) {
int
i=
0
;
if
(
3
>
2
|| (i++)>
0
){
System. out .println(i);
}
}
}
|
这个程序输出的i值是 0 原因是||在判断的时候,如果前面判断已经为true,那么就不会再判断后面的语句是否为真,那么后面的语句就不会执行。
如果将||换成|,结果会是怎样的呢
1
2
3
4
5
6
7
8
9
10
|
public
class
Test1 {
public
static
void
main(String[] args) {
int
i=
0
;
if
(
3
>
2
| (i++)>
0
){
System. out .println(i);
}
}
}
|
结果输出i的值是1, 原因是|操作符在进行判断的时候,无论前面的表达式是否为真,都会去执行后面的语句,那么,i的值就会加1,变成1。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public
class
Test2 {
public
static
void
main(String[] args) {
// TODO Auto-generated method stub
int
i=
0
;
if
((i++>
2
) && (i++)>
2
){
System. out .println(
"i="
+i);
}
else
{
System. out .println(i);
}
}
}
|
结果输出i的值是1 原因是&&操作符在进行判断的时候,当第一个表达式为false的时候,就会直接判断整个表达式为false,就不会执行后面的语句了。
将&&换成&
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public
class
Test2 {
public
static
void
main(String[] args) {
// TODO Auto-generated method stub
int
i=
0
;
if
((i++>
2
) & (i++)>
2
){
System. out .println(
"i="
+i);
}
else
{
System. out .println(i);
}
}
}
|
结果输出i的值为2 原因就是&会将前后表达式的判断结果都进行比较,所以就会输出2.
原文:点击打开链接 https://www.2cto.com/kf/201504/390053.html