将表达式的结果分配给基元 [英] Assigning result of an expression to a primitive
问题描述
K.Sierra在她的书SCJP学习指南中提到我们知道一个文字整数总是一个int,但更重要的是,涉及任何int-sized或更小的表达式的结果总是一个int 。
K.Sierra in her book "SCJP Study Guide" mentions "We know that a literal integer is always an int, but more importantly, the result of an expression involving anything int-sized or smaller is always an int."
我已经开始尝试了,我对以下结果感到有些困惑:
I've started experimenting and I'm a little bit confused with the below results:
byte a = 1; // correct
byte b = 1 + a; // incorrect (needs explicit casting)
byte c = 1 + 1; // correct (I expected it to be incorrect)
有人可以向我解释为什么最后一个例子做了不需要铸造?为什么Java编译器会进行隐式转换?是因为有2个文字?澄清非常感谢。
Could anyone explain to me why the last example does not require casting? Why does the Java compiler put the implicit cast? Is it because there are 2 int literals? Clarification greatly appreciated.
推荐答案
隐式类型转换只有在知道 RHS
的值时才有效在编译时
,表示它们是编译时常量
。在其他情况下,您需要进行明确的类型转换。
Implicit typecasting only works when the value of your RHS
is known at compile-time
, means they are compile-time constants
. In other cases, you need to do explicit typecasting.
所以: -
byte c = 1 + 1; // Value of `1 + 1` is known at compile time. Implicit cast
byte c = 1 + a; // Value of `1 + a` is evaluated at runtime. Explicit cast needed
另外,请注意,如果你声明你的变量 a
as 最后一个字节a = 1
,然后第二个作业将编译,就像那个案例一样,你的 a
将是编译时常量。
Also, note that, if you declare your variable a
as final byte a = 1
, then the 2nd assignment will compile, as in that case, your a
will be a compile time constant.
这篇关于将表达式的结果分配给基元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!