对常量求和时的隐式缩小与对变量求和时的显式缩小 [英] Implicit narrowing when summing constants vs explicit narrowing when summing variables

查看:77
本文介绍了对常量求和时的隐式缩小与对变量求和时的显式缩小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了一个程序.

class First
{
        public static void main(String[] args)
        {
                int c = 5;
                byte b = c+6;
                System.out.println(b);
        }
}

我的javac输出是:

And my javac output is:

error: incompatible types: possible lossy conversion from int to byte
        byte b = c+6;
                  ^
1 error

但是如果我将该程序修改为:

But if I modify the program as:

class First
{
        public static void main(String[] args)
        {
                byte b = 5+6;
                System.out.println(b);
        }
}

执行正常,输出:

11

我知道在操作之前,两个操作数都将转换为整数.然后,+运算符将得出一个整数.但是,如果变量c是整数,则默认情况下常数5也是整数.为什么在第二种情况下javac不会导致错误?

I know that before operation, both operands gets converted in integer. Then the + operator results in an integer. But if the variable c was an integer, then the constant 5 is also an integer by default. Why does not javac results an error in the second case?

如果我在概念上错了,请指导我.

Please guide me if I am conceptually wrong.

推荐答案

根据

常量表达式的编译时范围变窄意味着代码如下:

The compile-time narrowing of constant expressions means that code such as:

byte theAnswer = 42;被允许.如果不进行缩小,则整数文字42具有int类型的事实意味着将需要强制转换为字节:

byte theAnswer = 42; is allowed. Without the narrowing, the fact that the integer literal 42 has type int would mean that a cast to byte would be required:

byte theAnswer =(byte)42;//允许但不强制转换

byte theAnswer = (byte)42; // cast is permitted but not required

由于表达式 5 + 6 是一个适合 byte 范围的常量表达式,因此在编译时将自动将其范围缩小,而无需显式强制转换.另一方面,由于表达式 c + 6 不是常数表达式,因此不会自动将其变窄,并且需要显式强制转换.

Since the expression 5+6 is a constant expression that fits within the range of byte, it will automatically be narrowed at compile time without the need of an explicit cast. On the other hand, since the expression c+6 is not a constant expression, it will not be automatically narrowed and an explicit cast is required.

这篇关于对常量求和时的隐式缩小与对变量求和时的显式缩小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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