为什么指定'int constant - >字节变量'有效,但'长常数 - > int变量'不是? [英] Why is assigning 'int constant -> byte variable' valid, but 'long constant -> int variable' is not?

查看:194
本文介绍了为什么指定'int constant - >字节变量'有效,但'长常数 - > int变量'不是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个程式码片段:

int i = 5l; // not valid (compile error)
byte b = 5; // valid

你觉得怎么样?

为什么?

推荐答案

这在 JLS#5.2(作业转换)


如果表达式是byte,short,char或int类型的常量表达式(§15.28),如果变量的类型是byte,short ,或char,常量表达式的值可以在变量类型中表示。

If the expression is a constant expression (§15.28) of type byte, short, char, or int, a narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

b
$ b

so:

byte b = 5; //ok: b is a byte and 5 is an int between -128 and 127
byte b = 1000; //not ok: 1000 is an int but is not representable as a byte (> 127)
byte b = 5L; //not ok: 5L is a long (and not a byte, short, char or int)
int i = 5L; //not ok: i is not a byte, short or char
int i = 5; byte b = i; //not ok: i is not a constant
final int i = 5; byte b = i; //ok: i is a constant and b is a byte

这篇关于为什么指定'int constant - >字节变量'有效,但'长常数 - > int变量'不是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆