Java中是否有数字的默认类型 [英] Is there a default type for numbers in Java
问题描述
如果我写这样的东西
System.out.println(18);
哪种类型有18"?是int 还是byte?或者它还没有类型?
Which type has the '18'? Is it int or byte? Or doesn't it have a type yet?
它不能是 int,因为这样的东西是正确的:
It can't be int, because something like this is correct:
byte b = 3;
这是不正确的:
int i = 3;
byte bb = i; //error!
我想我在 赋值转换 :
常量的编译时收缩意味着代码如下:
The compile-time narrowing of constants means that code such as:
byte theAnswer = 42;
byte theAnswer = 42;
是允许的.如果没有缩小,整数文字 42 的类型为 int 的事实意味着需要强制转换为字节:
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;//强制转换是允许的,但不是必需的
byte theAnswer = (byte) 42; // cast is permitted but not required
推荐答案
这个
18
被称为 整数文字.有各种各样的文字、浮点数、String
、字符等
is known as an integer literal. There are all sorts of literals, floating point, String
, character, etc.
以下,
byte b = 3;
文字 3
是一个整数文字.这也是一个常量表达式.由于 Java 可以判断 3
适合 byte
,因此它可以安全地应用 缩小原始转换 并将结果存储在 byte
变量中.
the literal 3
is an integer literal. It's also a constant expression. And since Java can tell that 3
fits in a byte
, it can safely apply a narrowing primitive conversion and store the result in a byte
variable.
在这个
int i = 3;
byte bb = i; //error!
文字 3
是一个常量表达式,但变量 i
不是.编译器只是简单地决定 i
不是一个常量表达式,因此不会特意计算它的值,转换为 byte
可能会丢失信息(如何将 12345
转换为 byte
?),因此不应被允许.您可以通过使 i
成为常量变量
the literal 3
is a constant expression, but the variable i
is not. The compiler simply decides that i
is not a constant expression and therefore doesn't go out of its way to figure out its value, a conversion to byte
may lose information (how to convert 12345
to a byte
?) and should therefore not be allowed. You can override this behavior by making i
a constant variable
final int i = 3;
byte bb = i; // no error!
或通过指定显式转换
int i = 3;
byte bb = (byte) i; // no error!
这篇关于Java中是否有数字的默认类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!