一、赋值运算符
赋值运算符就是"="。用来为变量赋值。赋值要求类型匹配。
二、算术运算符
+、-、*(乘号)、/(整除)、%(取余)
1、没有小数点的运算
class Test{
public static void main(String[] args){
int x = 5;
int y = 7;
System.out.println("x + y = " + (x + y));
}
}
class Test{
public static void main(String[] args){
int x = 7;
int y = 5;
System.out.println("x / y = " + (x / y));
}
}
取整就是取结果的整数部分(包括符号),不进行四舍五入
class Test{
public static void main(String[] args){
int x = -8;
int y = 3;
System.out.println("x / y = " + (x / y));
}
}
求余就是取分子除去分母后的余数,符号与分子相同。
class Test{
public static void main(String[] args){
int x = 8;
int y = 3;
System.out.println("x % y = " + (x % y));
}
}
2、有小数点的运算
浮点加减是不精确。
class Test{
public static void main(String[] args){
double x = 8.3;
double y = 3.7;
System.out.println(x - y);//4.6000000000000005
}
}
class Test{
public static void main(String[] args){
float x = 8.3f;
double y = 3.7;
System.out.println(x - y);
}
class Test{
public static void main(String[] args){
float x = 8.3f;
float y = 3.7f;
System.out.println(x - y);
}
class Test{
public static void main(String[] args){
double x = 8.3;
float y = 3.7f;
System.out.println(x - y);
}
除,可以去除零。
class Test{
public static void main(String[] args){
double x = 8.3;
double y = 0;
System.out.println(x / y);
}
}
求余,也可以对零进行求余。
class Test{
public static void main(String[] args){
double x = 8.3;
double y = 0;
System.out.println(x % y);
}
}
三、复合赋值运算符
就是算术运算符和赋值运算符进行结合。
+=、-=、*=、/=、%=
y += x等同于y = y + x;
class Test{
public static void main(String[] args){
double x = 8.3;
double y = 3.2;
y += x;//y = y + x;
System.out.println("y = " + y);
}
}
class Test{
public static void main(String[] args){
double x = 8;
double y = 3;
y *= x + 4;//y = y * (x + 4)
System.out.println("y = " + y);
}
}
四、自加和自减
a++,a--;
++a,--a;
a++就是先使用a里面的值,再让a加1;
++a就是先让a加1,再使用a里面的值。
class Test{
public static void main(String[] args){
int x = 8;
System.out.println("x = " + x++);
}
}
System.out.println("x = " + x++);等同于
System.out.println("x = " + x);
x = x + 1;
class Test{
public static void main(String[] args){
int x = 8;
System.out.println("x = " + (x++ + x++));
}
}