学习大纲
- 逻辑运算符
- 位运算符
- 字符串连接符
- 条件运算符(三元运算符)
学习笔记
关于逻辑运算符
运算符
逻辑与 &
逻辑或 |
逻辑非 !
逻辑异或 ^
短路与 &&
短路或 ||
短路与和短路或的运算方式:都是从左往右计算,如果只通过左边的操作数就可以该逻辑表达式的值,则不会继续计算运算符右边的操作数,提高效率
关于位运算符
- 位运算符是对二进制进行运算的操作
位运算符
~
&
|
^
<<
/ >>
字符串不是数据类型,而是对象
关于字符串连接符
- 字符串连接符:+
- “+”运算符两侧的操作数中,只要有一个是字符串(String)类型,系统会自动将另一个操作数转换为字符串然后再进行连接
关于条件运算符
- 条件运算符是一个三元运算符
- 它的表达形式: x ? y : z
其中x为boolean类型表达式,先计算x的值,若为true,则整个运算的结果返回y的值,反之则为z的值
代码
TestOperation03
/**
*
- 测试逻辑运算符
- @author Administrator
*/
public class TestOperation03 {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
//System.out.println(!a);
/*boolean c = true;
boolean d = false;
System.out.println(a&b);
System.out.println(a&c);
System.out.println(a|b);
System.out.println(d|b);
System.out.println(a^b);
System.out.println(d^b);//异或是两个操作数不相同的值为true
*/
//测试逻辑与和逻辑或
//System.out.println(3/0);程序出现异常,中止,因为3/0在数学上有问题
//boolean a1 = 1>2 && 2<3/0;//最终得到了结果,同时程序报了异常
//boolean b2 = 1>2 || 2>3/0;//程序报了异常,同时没有得出结果!
System.out.println(!a);
}
}
TestOperation04
/**
*
- 测试位运算符
- @author L
*/
public class TestOperation04 {
public static void main(String[] args) {
int a = 3;
int b = 4;
System.out.println(a&b);
System.out.println(a|b);
System.out.println(~a);//这里出现负数会涉及到反码补码的知识,以后会了解
System.out.println(a^b);
//测试移位运算
System.out.println(12<<1);
System.out.println(12>>1);
}
}
TestOperation05
/**
*
- 测试字符串连接符
- @author L
*/
public class TestOperation05 {
public static void main(String[] args) {
String a = “3”;
int c = 3;
int b = 4;
char d = ‘a’;
System.out.println(a+b);//得到的结果实际是一个字符串
System.out.println(a+c);//这两条语句中都体现了b,c被转化为字符串的现象
System.out.println(c+b);//结果为数值
System.out.println(a+b+c);//一串字符串,因为先运行到a,所以将后面的转化为字符串进行运行
System.out.println(b+c+a);//先进行b+c=7的数值运算,然后运行到a时,数值7转化为字符串,与a进行拼接
System.out.println(‘d’+5);//在前面提到过,char类型的进行算数运算时会作为整数来看的
}
}
TestOperation06
/**
*
* 测试条件运算符(三元运算符)
- @author Administrator
*/
public class TestOperation06 {
public static void main(String[] args) {
int score = 80;
int x = -100;
String type = score < 60 ? “不及格” : “及格” ;//注意返回什么类型的值就要用什么类型去声明变量
//String a = score < 60 ? 1 : 2;程序报错,用于检验上一条的注释
System.out.println(type);
if(score<60) {
System.out.println("不及格");
}
else {
System.out.println("及格");
}
System.out.println(x>0 ? 1 : (x==0 ? 0 : -1));//条件运算符可以用于很复杂的运算,但是为了程序的简洁明了,不推荐这么做
}
}