运算符
这一篇,我们来学习Java的运算符
Java支持的运算符
1. 算术运算符
+:表示相加,表示正数,进行字符串拼接
public class demo {
public static void main(String[] args) {
System.out.println(+5);
System.out.println(-5);
//相加
int a = 5;
int b = 5;
System.out.println("相加结果:"+a+b+"\n"+"字符串拼接");
}
}
-:
表示相减操作
public class demo {
public static void main(String[] args) {
int a = 5;
int b = 5;
System.out.println("相减结果:"+a-b+"\n"+"字符串拼接");
}
}
* :
表示相乘操作
public class demo {
public static void main(String[] args) {
int a = 5;
int b = 5;
System.out.println("相乘结果:"+a*b+"\n"+"字符串拼接");
}
}
/:
相除操作
public class demo {
public static void main(String[] args) {
int a = 20;
int b = 5;
System.out.println("相除结果:"+a/b+"\n"+"字符串拼接");
}
}
%:
取余操作,取余数
public class demo {
public static void main(String[] args) {
int a = 12;
int b = 5;
System.out.println("取余结果:"+a%b+"\n"+"字符串拼接");
}
}
++
public class demo {
public static void main(String[] args) {
int a = 10;
a++;//a=a+1
System.out.println(a);
++a;//a=a+1
System.out.println(a);
//++运算符在单独使用时,放在前后都是加1操作。
int b = 10;
//在运算中,++在前,先加1再运算,++在后,先运算再加1
System.out.println(++b*a);
}
}
--
public class demo {
public static void main(String[] args) {
int a = 10;
System.out.println(--a*10);//先减一再运算
int b = 20;
System.out.println(b--*10);//先运算再减一
System.out.println(b);
}
}
2. 赋值运算符
=:
int num = 20;
将等号右侧的值赋值给等号左侧的变量
3. 关系运算符
<
=
<=
==
!=
public class demo {
public static void main(String[] args) {
System.out.println(1>5);//false
System.out.println(2<5);//true
System.out.println(1>=5);//false
System.out.println(2<=5);//true
System.out.println(3==3);//true
System.out.println(4!=9);//true
}
}
关系运算符最后的结果只有true或false
4. 逻辑运算符
&,|, &&,||,!,^
逻辑运算符,最终的结果也是布尔值,只有true或false
&:只要有一个操作数是false,那么结果一定是false
&&:只要第一个表达式是false,那么第二个表达式就不用计算了,结果一定是false
|:只要有一个操作数是true,那么结果一定是true
||:只要第一个表达式是true,那么第二个表达式就不用计算了,结果一定是true
!:相反结果
^:两个操作数相同,结果为false,不相同,结果为true
5. 条件运算符
a?b:c
如果a的结果是true,那么表达式最终结果为b
如果a的结果是false,那么表达式最终结果为c
public class demo {
public static void main(String[] args) {
int temp = 6;
int i = (3 + 2 != 5) ? temp = 9 : temp;
System.out.println(temp);
System.out.println(i);
}
}