+= operator in Java

Asked 2 years ago, Updated 2 years ago, 154 views

As far as I know, i+=j; and i=i+j have the same meaning

    int i = 5;
    long j = 8;

If I = i+j;, it can't be compiled. If I = j;, it runs well I wonder why.

java casting variable-assignment assignment-operator operator

2022-09-22 22:38

1 Answers

If you look at JLS ([link][jls]), you can see that a complex substitution operator, such as E1 + = E2, is a combination of: E1 = (Data type of E1) ((E1) op (E2)). So there's no problem with compiling. For example,

    short x = 3;
    x += 4.6;

Silver

    short x = 3;
    x = (short)(x + 4.6);

It changes in the same way.


2022-09-22 22:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.