java中的关系和逻辑运算:
运算符 | 用法 | 返回true的情况 |
> | op1>op2 | 大于 |
>= | op1>=op2 | 大于等于 |
< | op1<op2 | 小于 |
<= | op1<=op2 | 小于等于 |
== | op1==op2 | 等于 |
!= | op1!=op2 | 不等于 |
1》逻辑运算返回的都是boolean型的数据,即true or false;
2》逻辑运算是比较的对象(op)在计算机中内存的地址;
下面是一个例子:
public class FunnyTest {
public static void main(String[] args) {
char c='c';
System.out.println("+c ="+ +c);
byte b='c';
System.out.println("Initialized value +b ="+ +b);
System.out.println("(b==c) ="+(b==c));
byte w='w';
System.out.println("Initialized value +w ="+ +w);
b=w;
System.out.println("binds with w +b ="+ +b);
System.out.println("(c<=w) ="+(c<=w));
System.out.println("(c>=w) ="+(c>=w));
System.out.println("(b==c) ="+(b==c));
}
}
outprint:
Initialized value +c =99
Initialized value +b =99
(b==c) =true
Initialized value +w =119
binds with w +b =119
(c<=w) =true
(c>=w) =false
(b==c) =false
备注:此处‘+’ & ‘-’作为一元运算符
运算符 | 用法 | 描述 |
+ | +op | 如果op是一个byte,short,char,op变成int 型 |
- | -op | 取op的相反数 注:boolean型不适用 |
补充说明:4种条件运算符
运算符 | 用法 | 返回true的情况 |
&& | op1&&op2 | op1 和op2都是true |
|| | op1||op2 | op1 或者op2是true |
! | !op | op为false |
^ | op1^op2 | op1 和op2的逻辑值不同 |
条件运算符连接的关系是 逻辑关系
----------------------------------------------------------------------------------------------------------------------------------
有趣的代码:
public class FunnyTest {
public static void main(String[] args) {
double largeNum=Math.exp(4000.0);
double posDivZero=10.0/0.0;
double negDivZero=-10.0/0.0;
double zeroDivZero=0.0/0.0;
char c='c';
System.out.println("Initialized value +c ="+ +c);
System.out.println(largeNum);
System.out.println(posDivZero);
System.out.println(negDivZero);
System.out.println(zeroDivZero);
System.out.println("+c = "+ +c);
System.out.println("-c = "+ -c);
}
}
outprint:
Initialized value +c =99
Infinity
Infinity
-Infinity
NaN
+c = 99
-c = -99