开发者

Narrowing Type Conversion: Why is assignment of int to a byte in a declaration allowed?

This may sound too trivial for an intermediate Java programmer. But during my process of reviewing Java fundamentals, found a question:

Why is narrowing conversion like:

byte b = 13;

will be allowed while

int i = 13;
byte b = i;

will be开发者_如何转开发 complained by the compiler?


Because byte b = 13 ; is assignment of a constant. Its value is known at compile time, so the compiler can/should/will whine if assignment of the constant's value would result in overflow (try byte b = 123456789 ; and see what happens.)

Once you assign it to a variable, you're assigning the value of an expression, which, while it may well be invariant, the compiler doesn't know that. That expression might result in overflow and so the compiler whines.


From here:

Assignment conversion occurs when the value of an expression is assigned (§15.26) to a variable: the type of the expression must be converted to the type of the variable. Assignment contexts allow the use of an identity conversion (§5.1.1), a widening primitive conversion (§5.1.2), or a widening reference conversion (§5.1.4). In addition, a narrowing primitive conversion may be used if all of the following conditions are satisfied:

  • The expression is a constant expression of type byte, short, char or int.
  • The type of the variable is byte, short, or char.
  • The value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable.

In your example all three conditions are satisfied, so the narrowing conversion is allowed.

P.S. I know the source I'm quoting is old, but this aspect of the language hasn't changed since.


Because a literal number has no type.

Once you give it a type it must be casted to the other one:

int i = 13;
byte b = (byte) i;


A byte has 8 bits. An int, 32 bits, and it is a signed number.


Conversion from a number with a smaller range of magnitude ( like int to long or long to float ) is called widening. The goal of widening conversions is to produce no change in the magnitude of the number while preserving as much of the precision as possible. For example, converting the int 2147483647 to float produces 2.14748365e9 or 2,147,483,650. The difference is usually small, but it may be significant.

Conversely, conversion where there is the possibility of losing information about the magnitude of the number ( like long to int or double to long ) is called narrowing. With narrowing conversions, some information may be lost, but the nearest representation is found whenever possible. For example, converting the float 3.0e19 to long yields -9223372036854775807, a very different number.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜