gpt4 book ai didi

java - 了解缩小原始转换

转载 作者:行者123 更新时间:2023-11-29 06:59:15 26 4
gpt4 key购买 nike

我正在尝试理解 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com