为啥数字可以赋值给char

为啥数字可以赋值给char,比如char a = 134;不是说数字如果不写后缀默认就为int吗?int在java里是32位的怎么能赋值给16位的char呢?

阅读 3.9k
3 个回答

Assignment context

Assignment contexts allow the value of an expression to be 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 one of the following:

  • an identity conversion (§5.1.1)
  • a widening primitive conversion (§5.1.2)
  • a widening reference conversion (§5.1.5)
  • a widening reference conversion followed by an unboxing conversion
  • a widening reference conversion followed by an unboxing conversion, then followed by a widening primitive conversion
  • a boxing conversion (§5.1.7)
  • a boxing conversion followed by a widening reference conversion
  • an unboxing conversion (§5.1.8)
  • an unboxing conversion followed by a widening primitive conversion

If, after the conversions listed above have been applied, the resulting type is a raw type (§4.8), an unchecked conversion (§5.1.9) may then be applied.

In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

  • A narrowing primitive conversion may be used if the variable is of type byte, short, or char, and the value of the constant expression is representable in the type of the variable.
  • A narrowing primitive conversion followed by a boxing conversion may be used if the variable is of type Byte, Short, or Character, and the value of the constant expression is representable in the type byte, short, or char respectively.

常量赋值有特殊的规则

如果能确定数值在范围内都是不需要强转的:

byte b1 = 127;
byte b2 = (byte) 128;

char c1 = 65535;
char c2 = (char) 65536;

final int i1 = 1;
char c3 = i1;

int i2 = 1;
char c4 = (char) i2;

你搞错了,char a = 134中的134是short,不是int。数字如果不写后缀默认就为int,是个错误的说法。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题