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
is known as an integer literal. There are all sorts of literals, floating point, String
, character, etc.
在下面,
byte b = 3;
文字 3
是一个整数文字。它也是一个不变的表达。由于Java可以判断 3
适合字节
,因此它可以安全地应用缩小基元转换并将结果存储在 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
转换为字节
?)因此不被允许。您可以通过使 i
一个常量变量来重写此行为
the literal 3
is a constant expression, but the variable i
is not. The compiler simply decides that since 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屋!