为什么我不能添加两个字节并得到一个int,我可以添加两个最后的字节得到一个字节? [英] Why can not I add two bytes and get an int and I can add two final bytes get a byte?

查看:206
本文介绍了为什么我不能添加两个字节并得到一个int,我可以添加两个最后的字节得到一个字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Java{
    public static void main(String[] args){
        final byte x = 1;
        final byte y = 2;
        byte z = x + y;//ok
        System.out.println(z);

        byte a = 1;
        byte b = 2;
        byte c = a + b; //Compiler error
        System.out.println(c);
    }
}

如果表达式的结果涉及任何int-sized即使两个字节的总和适合一个字节,或者更小也总是一个整数。

If the result of an expression involving anything int-sized or smaller is always an int even if the sum of two bytes fit in a byte.

当我们添加两个适合于a的最后一个字节时,为什么会这样? byte?
没有编译器错误。

Why does it happen when we add two final bytes that fit in a byte? There is no compiler error.

推荐答案

来自JLS 5.2分配转换


此外,如果表达式是byte,short,char或int 类型的常量表达式(第15.28节):
- 如果
变量的类型是byte,short或char,则可以使用缩小的原始转换,并且常量
表达式的值可以在变量的类型中表示。

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.

简而言之,表达式的值(在编译时已知,因为它我一个常量表达式)可以表示为byte的变量类型。

In short the value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable that is byte.

考虑你的表达式

 final byte x = 1;
 final byte y = 2;
 byte z = x + y;//This is constant expression and value is known at compile time

因此总和适合字节时不会引发编译错误。

So as summation fits into byte it does not raise an compilation error.

现在如果你这样做

final byte x = 100;
final byte y = 100;
byte z = x + y;// Compilation error it no longer fits in byte

这篇关于为什么我不能添加两个字节并得到一个int,我可以添加两个最后的字节得到一个字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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