1、基本赋值运算符课堂案例
public class OperatorDemo04 {
public static void main(String[] args) {
int a = 3;
int b = 4;
a = a + b;
System.out.println(a); // 7
System.out.println(b); // 4
}
}
2、扩展赋值运算符课堂案例
public class OperatorDemo04 {
public static void main(String[] args) {
int a = 3;
int b = 4;
b += a;// 相当于 b = b + a ;
System.out.println(a); // 3
System.out.println(b); // 7
short s = 3;
// s = s + 4; 代码编译报错,因为将int类型的结果赋值给short类型的变量s时,可能损失精度
s += 4; // 代码没有报错
//因为在得到int类型的结果后,JVM自动完成一步强制类型转换,将int类型强转成short
System.out.println(s);
int j = 1;
j += ++j * j++;//相当于 j = j + (++j * j++);
System.out.println(j);//5
}
}
扩展赋值运算符在将最后的结果赋值给左边的变量前,都做了一步强制类型转换。
public class TestSeven {
public static void main(String[] args) {
// 赋值运算符
// = 右侧的值给左侧变量,这个运算符是所有运算符里优先级最低。
int x = 100;
// =的右侧一共会出现四种情况
int j = 10;// 常量值赋值
int y = j + x;// 表达式结果赋值
int z = y;// 变量值赋值
System.out.println("z="+z);// 变量给变量赋值也叫值传递,将值复制一份,将副本传递给新的变量。
// int w = input.nextInt()// 方法的返回值给变量赋值
// +=
int one = 100;
one += 10;// one = one + 10;
System.out.println("one="+one);
int two = 20;
double three = 12.5;
//two += three;//结果为32,因为会按照two的类型在运算前事先进行类型转换即:two = (int) (two + three);
//two = two + three;//报错,因为three为double类型,因此我们可以使用two += three;事先就给我们进行类型转化从而不会报错
System.out.println("two="+two);
}
}
130

被折叠的 条评论
为什么被折叠?



