赋值上下文中的Java原始转换Long和int [英] Java Primitive conversions in assignment context Long and int

查看:468
本文介绍了赋值上下文中的Java原始转换Long和int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Long ll = 102; // Error
Byte bb = 101; // No error

为什么分配是导致编译时错误,而字节分配没问题?

Why Long assignment is resulting in compile time error while Byte assignment is fine?

Long ll = 102 导致编译器错误类型不匹配:无法从int转换为Long。我假设编译器会将102扩展到 long ,然后将框加到 Long
但它没有发生。

Long ll = 102 is resulting in compiler error "Type mismatch: cannot convert from int to Long". I assumed compiler will widen of 102 to long and then box to Long. But it is not happening.

但是 Byte bb = 101; 没有产生编译器错误。在这里我猜,101缩小到 byte (非长整数常量),然后装箱到字节
当缩小没有问题时,扩大有什么问题?

But Byte bb = 101; is not generating compiler error. Here I guess, 101 is narrowed to byte (being non-long integral constant) and then Boxed to Byte. When there is no problem with narrowing, what is the problem with widening?

推荐答案

参见5.1.7 JLS的拳击转换



  • 如果p是int类型的值,则装箱转换将p转换为类的引用r并输入Integer,这样r.intValue()== p

因为 102 是一个整数字面值,它的类型是 int 并且自动装箱会将其转换为整数(作为spec说),但整数无法投放到 Long

Because 102 is an integer literal, it's type is int and auto boxing will convert it to Integer (as the spec says), but an Integer can not be casted to Long.

因此,当您使用 long 文字或将 int 字面值转换为时long JLS将使用装箱转换,结果将是 Long 对象。

Thus when you use a long literal or cast the int literal to long the JLS will use the boxing conversion and the result will be a Long object.

这没关系

Long long1 = (long) 102;
Long long2 = 102L;
Long long3 = 102l;

第二个

Byte bb = 101;

有效,因为5.2。分配转换


此外,如果表达式是byte类型的常量表达式(第15.28节),short,char,或int:

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


  • 如果变量的类型是byte,short或char,则可以使用缩小的原始转换,并且常量表达式可以在变量的类型中表示。

所以 101 是一个整数字面值,但有一个需要缩小转换(int - > byte)的赋值, int 的值在字节价值范围。因此,它可以表示为变量类型(请参阅规范)并进行转换。

So 101 is a integer literal, but there is an assignment that needs a narrowing conversion (int -> byte) and the value of the int is within the byte value range. Thus it is representable as the variable type (see spec) and it is converted.

这将 NOT WORK 当然

 Byte bb = 128; // can not be represented as the variable type. Thus no narrowing conversion.

这篇关于赋值上下文中的Java原始转换Long和int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆