Java编译问题
可能的重复:
为什么要使用 int我 = 2147483647 + 1;没问题,但是字节 b = 127 + 1;无法编译?
我是java初学者,所以请欣赏这个初学者问题。但为什么我的编译器对 byte b = 127 + 1; 不好?但使用 int i = 2147483647 + 1 编译得很好;
Possible Duplicate:
Why 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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的编译器会抱怨,因为它看到两个 int 被加在一起 (int 127) 和 (int 1),然后它担心在尝试将结果 (int 128) 存储到字节中时会丢失一些精度。
您选择的数字往往暗示您认为它与溢出有关。事实并非如此,即使在编程时牢记溢出很重要,编译器也不会抱怨溢出问题。
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.
因为当编译器看到 127 时,它会将其视为 int,而不是字节。您需要进行强制转换才能将结果放回字节中。
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.