小白学java 第四天
1,运算符
-
java语言支持以下运算符
-
算数运算符:+ , - ,*,/,%,++,——。
// 二元运算符 //复制当前行 到下一行 Ctrl+D 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);// 避免产生小数时的舍入。
补充,++,–,解释:
package operator; public class Demo03 { public static void main(String[] args) { // ++ -- 自增,自减 , 一元运算符。 int a = 5; int b = a++; // 先给b赋值 ,才进行的 自增 int c = ++a; //这里的a 是执行过a++的 a,++a要先进行自增再赋值 // a++ 先用再加,++a 先加再用。 System.out.println(b); System.out.println(c); // 幂运算 3^6 需要使用数学方法 Math.pow double pow = Math.pow (3,6); System.out.println(pow); } }
a++:先赋值,再自增。
++a:先自增,再赋值 -
赋值运算符:=。
-
关系运算符:>,<,>=,<=,==(java中的等于号),!=instanceof。
package operator; public class Demo02 { public static void main(String[] args) { long a = 199999999L; int b = 123; short c = 10; byte d = 8; System.out.println(a+b+c+d);// long 类型 System.out.println(b+c+d);//int System.out.println(c+d);// int System.out.println((double)c+d);// double // 有long 为long ,没有就为int, System.out.println("======================================="); // 关系运算符返回的结果: 正确 错误 布尔值(Boolean) int e = 10; int o = 20; System.out.println(e>o);//false System.out.println(e<o);// true System.out.println(e==o);//false System.out.println(e!=o);// true // 取余 % ,也叫模运算 int f =11; System.out.println(o%f);//输出9 } }
-
逻辑运算符:&&(于),||(或),非。
-
位运算符:&,|,^ , ~ , << , >> , >>> ,(了解)。
package operator; public class Demo04 { public static void main(String[] args) { boolean a = true; boolean b = false; // 与&& 或|| 非! System.out.println(a&&b); // (逻辑与运算)两个变量都为真 结果才为真,只要有一个为假结果为假。 System.out.println(a||b); // (逻辑或运算)有真为真 ,双假为假。 System.out.println(!b); // 真变假 ,假变真 // 逻辑左移<<,和,逻辑右移>> //效率极高!!! /* 0000 0001 0000 0010 2 0000 0100 0000 1000 0001 0000 16 */ System.out.println(2<<3); //因为逻辑右移三格,所以此时输出16 } }
-
条件运算符:?:,
package operator; public class Demo05 { 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); // 当a+b前有字符串时,会将a,b,转换成字符串类型,所以会输出1020 System.out.println(a+b+""); //此时字符串在a+b之后 ,会先进行a+b,所以会输出30 // 三元运算符 // x ? y : z // 如果x==true,则结果为y,否则为z, int score = 80; String type = score<60?"不及格":"及格"; System.out.println(type);// 80>60所以返回及格 } }
-
扩展赋值运算符:+= , -= , *= , /= .
-
运算符的优先级:
-