一、可以连续赋值
public class datatype { public static void main(String[] args) { int m = 1; int n = 1; int l = 1; m = n =l=8; System.out.println(m+n+l); } }
输出:
二、拓展赋值运算符
扩展赋值运算符: +=, -=, *=, /=, %= (字符串只有+= ,其实就是拼接)
public class datatype { public static void main(String[] args) { int m = 1; m = m +1; int k =1; k += 1; // 这里表示k 再次赋值为加上等于号后面的数字 System.out.println(m); System.out.println(k); } }
输出结果:
三、变量赋值与运算
数字类型的运算中,多个相同类型变量参与的运算,变量要先转换为相对应的数据类型的默认类型(比如两个byte类型的变量相加,会先把两个byte类型的变量转换成默认的int类型之后再计算,得到的结果是int类型。
public class datatype { public static void main(String[] args) { short o = 1; o = o+1; //* 运行时,系统报错,因为o=o+1 属于运算,系统默认会把运算的结果o改成int,但是与=左边o是short冲突;这里可以用o += 1,
因为它会强制将最后的o改为当前的类型*// System.out.println(o); short a =1; short b =1; short c= a +b; // 同上,如果这里改成int 则不会报错。 System.out.println(c); } }
四、i++ ++i i=i++ i =++i 的区别
相关区别和总结见批注:
public class datatype { public static void main(String[] args) { int c =5; c = 5+1; System.out.println(c); int o = 10; o++; // 相当于 o+=1 System.out.println(o); int p = 15; ++p; // 相当于p+=1 System.out.println(p); int a =20; a = a++; // 先取值,a=a=20,后运算,既然只有1个变量a,而且a大小确定了,也就没有后运算了。 System.out.println(a); int b =25; // 先运算 后取值 b=1+25=26 。后取值 ,只有1个变量,而且a大小也确定了 b = ++b; System.out.println(b); int q = 30; int r=++q; // 先运算r=30+1=31 然后赋值 r=q 所以q也等于31 System.out.println(q); System.out.println(r); int s = 35; int t=s++; // 先赋值t=s=35,得出t=35,然后运算 s自己+1,所以s=36 System.out.println(s); System.out.println(t); } }
结果:
五、
public class Test { public static void main(String[] args) { int o = 1; o*=0.1; // 会被强制转换成int,结果是0.1,只保留整数就是0 System.out.println(o); } }
结果