运算符
Java语言支持如下运算符
- 算术运算符:+、-、*、/、%、++、–
- 赋值运算符:=
- 关系运算符:> , < , >= , <= , == , != , instanceof
- 逻辑运算符:&& 、 || 、 !
- 位运算符:& 、| 、^ 、~ 、》 、 《 、>>>
- 条件运算符:? 、:
- 扩展赋值运算符:+= 、-= 、*= 、 /=
实例
01
package Base;
public class Demo06 {
static long e = 1234567891011L;
static int f = 1234;
static short h = 123;
static byte m = 12;
public static void main(String[] args) {
//二元运算符
int a = 10;
int b = 20;
int c = 30;
int d = 10;
// System.out.println(a+b);
// System.out.println(a-b);
// System.out.println(a*b);
// System.out.println(a/(float)b);
System.out.println(e+f+h+m);//long
System.out.println(f+h+m);//int //没有long 则结果都会是int类型
System.out.println(h+m);//int
// System.out.println();
}
}
02
package Base;
public class Demo07 {
public static void main(String[] args) {
//关系运算符返回的结果:正确 错误 (布尔值)
int a = 10;
int b = 20;
int c = 25;
System.out.println(a>b);
System.out.println(a<b);
System.out.println(a==b);
System.out.println(a!=b);
}
}
特殊的自增自减运算
package Base;
public class Demo08 {
public static void main(String[] args) {
//++ -- 自增 自减 一元运算符
int a = 3;
int b = a++; //a++ , ++a 都是a=a+1
//a++,先把a赋值给b,再自增
//++a, a先自增再赋值给c
int c = ++a;
System.out.println(a);
System.out.println(b);
System.out.println(c);
//幂运算 2^3=8在JAVA中是不行的 因为^是JAVA中的异或运算
double m = Math.pow(2,3); //2的3次方
double n = Math.pow(3,2);
System.out.println(m);
System.out.println(n);
}
}
短路运算符
短路运算符就是我们常用的“&&”、“||",一般称为”条件操作“。
eg
class Logic{
public ststic void main(String[] args){
int a=1;
int b=1;
if(a<b && b<a/0){
System.out.println("Oh,That's Impossible!!!");
}else{
System.out.println("That's in my control.");
}
}
}
“&&“运算符检查第一个表达式是否返回"false”,如果"false"则结果必为"false"不再检查其他内容。 此处"a/0"是个明显的错误!但短路运算”&&“先判断"a<b”,返回"false",遂造成短路,也就不会进行"b<a/0"的操作了,程序会打出"Oh,That’s Impossible!!!"。这个时候,交换一下"&&"左右两边的表达式,程序立即抛出异常 “java.lang.ArithmeticException: / by zero”。