开发者

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
    开发者_如何学C    System.out.println(b);  
    }
}

I am using this code but I have problem: I don't understand why b=b+l; is not compiling but if I write b+=l; then it compiles and runs.

Please explain why this happens.


b+=1 does type casting automatically in Java; b=b+1 does not.


This is what the advantage of compound assignment operators like +=, -= ,etc over assignment operators, where you have to explicitly cast to the type of the right hand side but if you use compound assignment operator it implicitly does it for you. As it is happening in your case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜