Java基础:运算符
算数运算符:+,-,*,/,%,++,--
赋值运算符:=
关系运算符:>,<,>=,<=,==,!=,instanceof
逻辑运算符:&&,||,!
位运算符:&,|,^,~,>>,<<,>>>
条件运算符: ?:
扩展赋值运算符:+=,-=,*=,/=
package operator; public class Demo1 { public static void main(String[] args) { //二元运算符 //Ctrl+D:复制当前行到下一行(仅IEDA) 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((double)a/b); System.out.println("==================="); long a1 = 1212121212121L; int b1= 123; short c1= 10; byte d1= 8; //+运算:带long的输出位long,没有long的都为int System.out.println(a1+b1+c1+d1);//long System.out.println(b1+c1+d1);//int System.out.println(c1+d1);//int //cast:转换 System.out.println("==================="); //关系运算符返回结果:布尔型:false,true int e=10; int f=20; int g=21; System.out.println(e>f); System.out.println(e<f); System.out.println(e==f); System.out.println(e!=f); System.out.println(g%e);//取余:21%10=1 21/10=2...1 System.out.println("====================="); //++ -- 自增 自减 一元运算符 int a2=3; System.out.println(a2); int b2=a2++;//先赋值后自增 //a++: a = a + 1; System.out.println(a2); int c2=++a2;//先自增后赋值 //++a: a = a + 1; System.out.println(a2); System.out.println(b2); System.out.println(c2); System.out.println("===================="); //幂运算 2^3 2*2*2=8 double pow=Math.pow(3,2);//Math数学类,pow幂运算 System.out.println(pow); System.out.println("===================="); //逻辑运算符 //与(&&)或(||)非(!) boolean z=true; boolean s=false; System.out.println("z&&s:"+(z&&s));//逻辑与运算:两个变量都为真,结果才为真 System.out.println("z||s:"+(z||s));//逻辑或运算:两个变量有一个为真,结果才为真;两个变量都为假,结果才为假 System.out.println("!(z&&s):"+!(z&&s));//逻辑非运算:如果真则变假,如果假则变真 //短路运算 //逻辑与运算第一个变量为false,则后面变量就不会再运算 int q=5; boolean w=(q<4)&&(q++<4);//回顾自增自减 System.out.println(w);//false System.out.println(q);//5 System.out.println("====================="); //位运算 /* A=0011 1100 B=0000 1101 -------------------- A&B=0000 1100 A.B同为1则A&B为1 与 A|B=0011 1101 A.B同为0则A|B为0 或 A^B=0011 0001 A.B相同则A^B为0 异或 ~B=1111 0010 取反 ----------------------- 2*8=16 2*2*2*2 效率极高 << 左移 *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); System.out.println("======================"); //偷懒运算符+= -= *= /= int num1=10; int num2=20; num1+=num2;//num1=num1+num2; num2-=num1;//num2=num2-num1; System.out.println(num1); System.out.println(num2); System.out.println("======================"); //字符串连接符 + String System.out.println(""+num1+num2);//30-10 ""在前拼接 System.out.println(num1+num2+"");//20 ""在后运算 System.out.println("======================"); //三元运算符?: //x?y:z //如果x==true,则结果为y,否则结果为z int score=50; String type=score<60?"不及格":"及格";//必须掌握 System.out.println(type); } }