关系运算符 > ,< ,>=, <=, !=, ==
逻辑运算符:与:&& (&),或: ||( |) ,非:!
返回的都是布尔值,java中是没有1和0 来代表true 或false的。
一、关系运算符
== 是用来比较数值的大小:
对于基本数据类型 比较的是数值
对于引用数据类型 比较的是地址
注意:string,字符串比较特殊,比较值不能使用==,必须使用equals方法
public class demo2 {
public static void main(String[] args) {
String stra ="abc";
String strb = new String("abc");
String strc = new String("abc");
String strd = "abc";
System.out.println(stra==strd);//true
System.out.println(stra==strb);//false
System.out.println(strb==strc);//false
System.out.println(stra.equals(strb));//true
}
}
原理:
(1)当声明一个变量 String stra ="hello"的时候, 会将“hello”这个字符串放在变量池中,当再声明String strd = “hello”的时候,会自动去变量池寻找是否有hello, 因此比较stra==strd, 它们的地址是一样的。
(2) 当声明一个新的变量String strb = new String(“hello”) 的时候,会将String(“hello”)放在堆里面,声明一个新的就存一次,地址不会一样的。但是值是一样的。
二、逻辑运算符
public class demo2 {
public static void main(String[] args) {
int a = 19;
if(true && a>20) {
System.out.println("t");
} // 如果为真与a>20都满足的时候,就输出t
//&& 短路与,当前面那个是假的时候,后面的表达式就不会理它了,这是为了提高代码的效率
if(a!=20 && a++>10) {
System.out.println("t");//如果满足a不等于20与a++>10,就输出t
//如果a不等于20为假的时候,后面的就不会理会了。
}
//& 相对于&& 不同的是,表达式两边都会去执行判断
if(false & a++>10) {
System.out.println("t");
}
// ||短路或,当前面的是真,则后面的表达式不去理会了
if(true || a++>0) {
System.out.println("t");
}
}
}