Java语言运算符
- 算数运算符:+ - * / % ++ --
- 赋值运算符: =
- 关系运算符: < ,>,>=,<=,==,!= ,instanceof
- 逻辑运算符:&&,||,!
- 位运算符:&,|,^,~
- 条件运算符:?
- 扩展复制运算符:+=,-=,*=,/=
package base; public class Demo0 { public static void main(String[] args) { int a = 5; int b = 10; int c = 10; int d = 10; System.out.println(a+b); System.out.println(a-b); System.out.println(a*b); System.out.println(a/(double)b); } }
a++和a--
package base; import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput; public class Demo02 { public static void main(String[] args) { // ++ 自增 // -- 子减 int a = 3; int b = a++;//a++ a = a+1,执行完这行代码,先给b赋值,再自增 System.out.println(a); int c = ++a;//先自增,再给b赋值 System.out.println(a); System.out.println(b); System.out.println(c); } }
幂运算
package base; import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput; public class Demo02 { public static void main(String[] args) { double pow = Math.pow(2, 8); System.out.println(pow); } }
逻辑运算
package base; import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput; public class Demo02 { public static void main(String[] args) { //与(and),或(or),非(取反) boolean a = true; boolean b = false; System.out.println("a && b"+(a&&b));//逻辑与运算,两个变量都为真,结果才为true System.out.println("a || b"+(a||b));//逻辑或运算,两个变量有一个为真,结果才为true System.out.println("!(a && b)"+!(a&&b));//如果都为真,则变成加,如果是假则变为真 //短路运算 int c = 5; boolean d = (c<4)&&(c++<4); System.out.println(c); System.out.println(d); } }
三元运算符
package base; public class Demo03 { 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+"");//+在数值后面数值会运算 //x?y:z如果x==true,则结果为y,否则为z int score = 80; String type = score<60 ? "不及格":"及格"; System.out.println(type); } }