JAVA支持的运算
算数运算符
+, - , * , /,自增(++),自减(–)
package operator;
public class Demo03 {
public static void main(String[] args) {
//自增 ++ 自减--
int a = 3;
int b = a++;//先将a赋值给b,再自增
System.out.println(a);//此时a=4
System.out.println(b);
int c = ++a;//先自增,再赋值给c
System.out.println(a);
System.out.println(c);
//幂运算 2^3 很多运算会借助Math的工具来做,比如pow的幂运算
double pow = Math.pow(2, 3);
System.out.println(pow);
}
}
简单的结果类型转换
package operator;
public class Demo01 {
public static void main(String[] args) {
//需要两个数的运算叫二元运算符
int a = 10;//Ctrl+D复制当前行到下一行
int b = 20;
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a*b);
System.out.println(a/b);//a和b是int型所以结果取了整数部分
System.out.println(a/(double)b);
System.out.println((double) a/b);
System.out.println((double) (a/b));//这个结果是(a/b)之后再转的double
}
}
package operator;
public class Demo02 {
public static void main(String[] args) {
Long a = 4008123123L;
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型(除了Long以外,其它类型的结果都为int型)
}
}
自增和自减 外加幂运算
package operator;
public class Demo04 {
public static void main(String[] args) {
int a = 3;
int b = a++;//先将a赋值给b后,a再++
System.out.println(a);
System.out.println(b);
int c = ++a;//先将a自增后,再赋值给c
System.out.println(c);
//幂运算 2^3 很多特殊运算会使用一些工具来做,比如pow
double pow = Math.pow(2, 3);//Alt+回车
System.out.println(pow);
}
}
与或非
package operator;
public class Demo05 {
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(!(a&&b));
//短路问题 &&如果前面那个已经是false了,后面就不用执行了
int c = 3;
boolean d = (c>4 && c++<10);
System.out.println(c);
System.out.println(d);
int e = 3;
boolean f = (e++>3 && e<2);
System.out.println(e);
System.out.println(f);
/*主要在二进制的运算
A = 0011 1100
B = 0000 1101
----------------
A&B = 0000 1100 同时为真则为真
A|B = 0011 1101 有1个为真则为真
A^B = 0011 0001 一真一假则为真
~B = 1111 0010 取反
---------------
效率极高的左移和右移
<< 相当于乘以2 0000 0001 左移一位 0000 0010
>> 相当于除以2 同上
*/
System.out.println(2<<3);
}
}