前言
Java基础学习笔记,仅供参考
一、运算符
1.逻辑运算与位运算
public class Day8 {
public static void main(String[] args) {
// 逻辑运算符 与(and) 或(or) 非(取反)
boolean a = true;
boolean b = false;
System.out.println("a && b: "+(a&&b)); // 两个都为真结果才为真,否则为假
System.out.println("a || b: "+(a||b)); // 有一个为真就为真,否则为假
System.out.println("! (a && b): "+!(a&&b)); // 是真则返回假,是假则返回真
// 短路运算
int c = 5;
boolean d = (c<4)&&(c++<4);
System.out.println(d);
System.out.println(c);
// 可以得出因才c<4为假,则该表达式则中断运算直接得出假,不会继续判断后面的表达式
// 位运算
/*
A = 0011 1100
B = 0000 1101
----------------------------
A&B = 0000 1100 位中的与运算,两个都为1则为1,其他为0
A|B = 0011 1101 位中的或运算,有至少一个为1则为1,其他为0
A^B = 0011 0001 位中的异或运算,相同为0,不相同为1
~B = 1111 0010 位中的取反运算,
2*8 = 16 如何运算的更快? 拆分为2*2*2*2
<< 向左移位 如4向左移位则变为8 *2
>> 向右移位 如4向右移位则变为2 /2
0000 0000 0
0000 0001 1
0000 0010 2
0000 0011 3
0000 0100 4
0000 1000 8
0001 0000 16
位运算的效率极高
*/
System.out.println(2<<3);
}
}
2.一元运算符
public class Day7 {
public static void main(String[] args) {
// ++ -- 自增,自减 一元运算符
int a = 3;
int b = a++; // 执行完这行代码前,先给b赋值,再自增
// 自增就相当于多了一行代码 a = a + 1
System.out.println(a);
int c = ++a; // 执行完这行代码前,先自增,再给b赋值
System.out.println(a);
System.out.println(b);
System.out.println(c);
// 幂运算 2^3
double pow = Math.pow(2,3);
System.out.println(pow);
}
}
3.二元运算符
public class Day6 {
public static void main(String[] args) {
// 二元运算法
// Ctrl + D : 复制当前行到下一行
int a = 10;
int b = 20;
int c = 30;
int d = 40;
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a*b);
// System.out.println(a/b); 这样的结果是0,因为数据类型是int
System.out.println(a/(double)b);
long a1 = 123123123123123L;
int b1 = 123;
short c1 = 10;
byte d1 = 8;
System.out.println(a1+b1+c1+d1); // Long 有long则为long,无则为int
System.out.println(b1+c1+d1); // Int
System.out.println(c1+d1); // Int
System.out.println(a<=b); // true
}
}
4.三元运算符与字符串连接
public class Day9 {
public static void main(String[] args) {
int a = 10;
int b = 20;
a+=b; // a = a + b
a-=b; // a = a - b
System.out.println(a);
// 字符串连接符 + ,当出现String时,则会全部转换为字符串相连
System.out.println(a+b); // 30 数字的加减
System.out.println(""+a+b); // 1020 字符串相连
System.out.println(a+b+""); // 30 如果字符串在后面,则先运算
// 三元运算符 x ? y : z
// 如果x==true,则结果为y, 否则为z
int score = 80;
String type = score < 60 ? "不及格":"及格"; // 比if判断精简
System.out.println(type);
}
}