理解缩小原始转换 [英] Understanding narrowing primitive conversion

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

问题描述

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

I'm trying to understand the narrowing primitive conversion concept in Java. Here's what the JLS 5.1.3 says about it:


原始类型的22个特定转换称为缩小的
原始转换:

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

短到字节或字符

字符到字节或短

int to byte,short或char

int to byte, short, or char

long to byte,short,char或int

long to byte, short, char, or int

float to byte,short,char,int或long

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

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

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

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

Since there is the implicit conversion converting long to int, we can write the following code:

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

DEMO

DEMO

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

But it doesn't work. Why? The narrowing conversion from long to int should have been applied.

推荐答案


由于存在隐式转换将long转换为int

Since there is the implicit conversion converting long to int

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

There isn't. There's an explicit conversion. Narrowing conversions aren't generally applied implicitly, precisely because they can lose information. So you'd need:

int c = (int) 88L;

确实, JLS第5部分的初始部分甚至给出了一个例子:

Indeed, the initial part of JLS section 5 even gives an example:

// 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;

在某些情况下, =http://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.2 =nofollow>赋值上下文(JLS 5.2)但是:

There are some cases where narrowing conversions are applied explicitly in assignment contexts (JLS 5.2) though:


此外,如果表达式是类型为 byte char int


  • 如果变量的类型是 byte short char ,并且常量表达式的值可在变量类型中表示。

  • 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.

如果变量的类型为:


  • 字节,常量表达式的值可在字节

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

...(类似于字符

这就是有效的原因即使文字 120 的类型是 int

That's why this is valid even though the type of the literal 120 is int:

byte x = 120;

将其与扩展转化进行比较,这些转化在分配上下文调用中是允许的上下文( JLS 5.3 ) 。

Compare that with widening conversions, which are permitted within assignment contexts and invocation contexts (JLS 5.3).

这篇关于理解缩小原始转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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