Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

后端 未结 11 1362
暖寄归人
暖寄归人 2020-11-21 05:06

Until today, I thought that for example:

i += j;

Was just a shortcut for:

i = i + j;

But if we try this:<

11条回答
  •  盖世英雄少女心
    2020-11-21 05:26

    A good example of this casting is using *= or /=

    byte b = 10;
    b *= 5.7;
    System.out.println(b); // prints 57
    

    or

    byte b = 100;
    b /= 2.5;
    System.out.println(b); // prints 40
    

    or

    char ch = '0';
    ch *= 1.1;
    System.out.println(ch); // prints '4'
    

    or

    char ch = 'A';
    ch *= 1.5;
    System.out.println(ch); // prints 'a'
    

提交回复
热议问题