如果我这样写
System.out.println(18);
哪种类型有“18”? 是 int 还是 byte? 或者它还没有类型?
它不能是 int,因为这样的东西是正确的:
byte b = 3;
这是不正确的:
int i = 3;
byte bb = i; //error!
编辑: 我想我在 Assignment Conversion 的规范中找到了正确的部分:
The compile-time narrowing of constants means that code such as:
byte theAnswer = 42;
is allowed. Without the narrowing, the fact that the integer literal 42 has type int would mean that a cast to byte would be required:
byte theAnswer = (byte) 42; // cast is permitted but not required
最佳答案
这个
18
被称为integer literal .有各种各样的literals , float , String
, 字符等
在下面,
byte b = 3;
文字 3
是一个整数文字。它也是一个常量表达式。由于 Java 可以判断 3
适合 byte
,因此它可以安全地应用 narrowing primitive conversion。并将结果存储在 byte
变量中。
在这
int i = 3;
byte bb = i; //error!
文字 3
是常量表达式,但变量 i
不是。编译器简单地决定 i
不是常量表达式,因此不会特意找出它的值,转换为 byte
可能会丢失信息(如何将 12345
转换为 byte
?),因此不应被允许。您可以通过使 i
成为常量变量
final int i = 3;
byte bb = i; // no error!
或者通过指定显式转换
int i = 3;
byte bb = (byte) i; // no error!
关于java - Java中是否有默认的数字类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27263070/