I have a problem with the following Java code

public class b {
    public static void main(String[] args) {
        byte b = 1;
        long l = 127;
    //  b = b + l;            // 1 if I try this then it does not compile
        b += l;               // 2 if I try this then it does     compile
        System.out.println(b);  
    }
}

I use this code, but I have a problem: I do not understand why it b=b+l;does not compile, but if I write b+=l;, then it compiles and runs.

Please explain why this is happening.

+3
source share
2 answers

This is the advantage of compound assignment operators like + =, = =, etc., over assignment operators, where you need to explicitly specify the type of the right side, but if you use the compound assignment operator, it implicitly does this for you. How does this happen in your case.

+1
source

b+=1Automatically creates automatically in Java b=b+1does not work.

+13
source

Source: https://habr.com/ru/post/1737878/


All Articles