Chapter: 08 Operator [assignment operators]

① symbol: =

☞ When the "=" both data types do not match, automatic type conversions may be used or a cast process principles.

☞ Support continuous assignment.

② extended assignment operator
+ =, - =, * =, / =,% = implied a cast

1 + = to the left and right to make additions, and then assigned to the left.

int y = 10;

y + = 20; // equivalent to y = (y data type) (y + 20);

System.out.println(y);//30

 

 

 

③ examples

/*

The two operators: assignment operator

=  +=  -=  *=  /=  %=

*/

class SetValueTest {

   public static void main(String[] args) {

       // assignment symbol: =

       int i1 = 10;

       int j1 = 10;

       int i2,j2;

       // continuous assignment

       i2 = j2 = 10;

       int i3 = 10,j3 = 20;

       //*********************

       int num1 = 10;

       num1 += 2;//num1 = num1 + 2;

       System.out.println(num1);//12

       int num2 = 12;

       num2% = 5; // num2 = num2 5%;

       System.out.println(num2);

       short s1 = 10;

       // s1 = s1 + 2; // fail to compile

       s1 + = 2; // Conclusion: does not change the data type of the variable itself

       System.out.println(s1);

       // development, if you want to achieve the operation +2 variable, there are several ways? (Prerequisite: int num = 10;)

       @ A manner: num = num + 2;

       //方式二:num += 2; (推荐)

       

       //开发中,如果希望变量实现+1的操作,有几种方法?(前提:int num = 10;)

       //方式一:num = num + 1;

       //方式二:num += 1;

       //方式三:num++; (推荐)

       

       //练习1

       int i = 1;

       i *= 0.1;//等价于  i = (int)( i* 0.1);

       System.out.println(i);//0

       i++;

       System.out.println(i);//1

       //练习2

       int m = 2;

       int n = 3;

       n *= m++; //n = n * m++;    

       System.out.println("m=" + m);//3

       System.out.println("n=" + n);//6

       

       //练习3

       int n1 = 10;

       n1 += (n1++) + (++n1);//n1 = n1 + (n1++) + (++n1);   10 +10 +12

       System.out.println(n1);//32

   }

}

 

④面试题

1、 short s=1;s = s+1;

    short s=1;s += 1;

    上面两个代码有没有问题,如果有,那里有问题。

    为什么第二个木有问题呢?

    扩展的赋值运算符其实隐含了一个强制类型转换。

    s += 1;

    不是等价于 s = s + 1;

    而是等价于 s = (s的数据类型)(s + 1);

    //short s = 1;

    //s = s + 1;

    //System.out.println(s);

    short s = 1;

    s += 1; //好像是 s = s + 1;

    System.out.println(s);

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 
 

 

 

 

 

 

 

 

 

 

 
 

 

Guess you like

Origin www.cnblogs.com/Lucky-stars/p/11007645.html