What is the difference between a+=b and a=a+b in the Java language?

Answer: There are differences, the main difference is the accuracy of operation caused by data type conversion

  1. When the two variables are of the same data type, there is no precision loss and deviation in the calculated results.

  2. When the two variables are of different data types, data type conversion will be carried out in the calculation process. The conversion follows the rules of “automatic type promotion” and “cast type conversion”, so there are precision loss and deviation in the calculation results.

  3. Code description:

    • The data type level of A is smaller than that of B and follows the cast rules

      public static void main(String[] args) {
              short a = 11;
              int b = 22;
              a += b;// Cast to short
              System.out.println(a);/ / 3
          }
      Copy the code
      public static void main(String[] args) {
              short a = 11;
              int b = 22;
              a = a + b;A = (short) (a + b); a = (short) (a + b);
              System.out.println(a);
          }
      Copy the code
    • The data type level of A is greater than that of B and follows the automatic type promotion rule

      public static void main(String[] args) {
              short a = 11;
              int b = 22;
              b += a;// Automatic type promotion to int
              System.out.println(b);/ / 33
          }
      Copy the code
      public static void main(String[] args) {
              short a = 11;
              int b = 22;
              b = a + b;// The data type level of short is lower than that of int
              System.out.println(b);/ / 33
          }
      Copy the code
  4. Type conversion supplement:

    Low -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - > high byte, short, char - > int - > long - > float - > doubleCopy the code