簡體   English   中英

我有以下Java代碼的問題

[英]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);  
    }
}

我正在使用此代碼,但我有問題:我不明白為什么b=b+l; 沒有編譯,但如果我寫b+=l; 然后它編譯並運行。

請解釋為什么會這樣。

b+=1在Java中自動輸入類型; b=b+1沒有。

這就是復合賦值運算符(如+ =, - =等)優於賦值運算符的優點,您必須明確地轉換為右側的類型,但如果使用復合賦值運算符,它會隱式為您執行此操作。 正如你的情況一樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM