public class Demo01 { public static void main(String[] args) { //二元运算符 //复制当前行到下一行 int a = 10; int b = 20; int c = 25; int d = 25; System.out.println(a+b); System.out.println(a-b); System.out.println(a*b); System.out.println(a/(double)b); //0.5,需要强转类型 }
运行结果:
public class Demo02 { public static void main(String[] args) { long a =1223233l; int b = 342; short c = 15; byte d = 7; System.out.println(a+b+c+d);//输出类型:long System.out.println(b+c+d);//int System.out.println(c+d);//short } }
运行结果:
public class Demo04 { public static void main(String[] args) { //++ -- 自增,自减 一元运算符 int a = 3; int b = a++; //执行代码后,先赋值,再自增 //a++ a = a + 1 System.out.println(a); //a = a + 1 int c = ++a; //执行代码前,先自增,再赋值 System.out.println(a); System.out.println(b); System.out.println(c); //很多运算,我们会使用工具类来进行操作 //幂运算 2^3 2*2*2 double pw = Math.pow(2,3); System.out.println(pw); } }
运行结果:
public class Demo03 { public static void main(String[] args) { //关系运算符的返回结果:正确和错误 布尔值 // if int a =10; int b =20; int c =21; System.out.println(c%a);//模运算(取余) 21/10=2...1 System.out.println(a>b); System.out.println(a<b); System.out.println(a==b); System.out.println(a!=b); } }
运行结果:
public class Demo05 { 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));//真边假 System.out.println("=============="); //短路运算 int c = 5; boolean d=(c<4)&&(c++<4);//c++没有执行,证明短路运算 System.out.println(c); System.out.println(d); } }
运行结果:
public class Demo06 { //位运算 /* A = 0011 1100 B = 0000 1101 ------------------------- A&B = 0000 1100 与 A|B = 0011 1101 或 A^B = 0011 0001 异或,相同为0 ~B = 1111 0010 取反 ---------------------------- 2*8 = 16 2*2*2*2 */ public static void main(String[] args) { System.out.println(2<<3); /* << 左移 *2 >> 右移 /2 0000 0000 0 0000 0001 1 0000 0010 2 0000 1000 8 0001 0000 16 */ } }
运行结果:
public class Demo07 { public static void main(String[] args) { int a = 10; int b = 20; a+=b;//a = a + b System.out.println(a); a-=b;//a = a - b System.out.println(a); //字符串连接符 + System.out.println(""+a+b); System.out.println(a+b+""); } }
运行结果:
public class Demo08 { //三元运算符 public static void main(String[] args) { //x ? y : z //如果x为真,则结果为y,否则为z int score = 80; String type = score < 60 ? "fail" : "success"; //if System.out.println(type); } }
运行结果: