java - 了解缩小原始转换

标签 java

我正在尝试理解 Java 中缩小的原始转换概念。这是 JLS 5.1.3 的内容说:

22 specific conversions on primitive types are called the narrowing primitive conversions:

short to byte or char

char to byte or short

int to byte, short, or char

long to byte, short, char, or int

float to byte, short, char, int, or long

double to byte, short, char, int, long, or float

由于存在将long转换为int的隐式转换,我们可以编写如下代码:

public static void main (String[] args) throws java.lang.Exception
{
    int c = 88L; //Compilation fail
    System.out.println(c);
}

DEMO

但它不起作用。为什么?应该应用从 long 到 int 的缩小转换。

最佳答案

Since there is the implicit conversion converting long to int

没有。有一个显式 转换。缩小转换通常不会隐式应用,正是因为它们可能会丢失信息。所以你需要:

int c = (int) 88L;

的确,initial part of JLS section 5甚至举个例子:

// Casting conversion (5.4) of a float literal to
// type int. Without the cast operator, this would
// be a compile-time error, because this is a
// narrowing conversion (5.1.3):
int i = (int)12.5f;

在某些情况下,在 assignment contexts (JLS 5.2)明确应用了收缩转换。虽然:

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 type of the variable is 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 type of the variable is:

    • Byte and the value of the constant expression is representable in the type byte.

    • ... (similar for Short and Character)

这就是为什么 this 即使 120 的类型是 int 也是有效的原因:

byte x = 120;

将其与扩大转换进行比较,后者在赋值上下文 调用上下文 ( JLS 5.3 ) 中是允许的。

关于java - 了解缩小原始转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28936802/

相关文章:

java - 使用 Google Guava Collections2.transform 的奇怪之处

java - 将 RGB 值转换为颜色

java - 是否溢出,与 >>> 运算符

Java多线程: How to make a thread wait ?

java - Maven:运行测试前检查参数

java - WebSphere 8.5.5数据库层(带参数调用函数或jpa中的select)

java - 替代配置不会更改 CentOS 中的 Java 版本

java - Google Chrome 移动版如何显示 Youtube 和 Twitch 等网站?

java - 我应该使用 SQL 中的每个循环/游标还是 Java 中的常规循环/游标?什么更有效?

java - 什么是 "java.sql.SQLException: No value specified for parameter 1 "?