开发者

Java compile question [duplicate]

开发者 https://www.devze.com 2023-03-25 09:52 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: W开发者_运维技巧hy int i = 2147483647 + 1; is ok, but byte b = 127 + 1; is not compilable?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

W开发者_运维技巧hy int i = 2147483647 + 1; is ok, but byte b = 127 + 1; is not compilable?

Im a beginner with java so please appreciate this beginner question. But why is my compiler not fine with byte b = 127 + 1; but compiles fine with int i = 2147483647 + 1;


Your compiler complains because it sees two ints being added together (int 127) and (int 1) and then it worries that some precision will be lost as it attempts to store the result (int 128) into a byte.

The numbers you selected tend to hint that you think it is related to overflow. It is not, as even if it is important to keep overflow in mind when programming, the compiler never complains about overflow issues.


because when the compiler sees 127 it treats it as an int, not a byte. You need a cast to fit the result back into a byte.

0

精彩评论

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