Java中用空格分隔的2字节变量相加背后的数学

Java中用空格分隔的2字节变量相加背后的数学,java,math,Java,Math,有人能解释一下这个代码中的数学运算结果是35吗 public class Main { public static void main(String[] args) { byte x = 1; byte y = 2; System.out.println(x + ' ' + y); }} 基本上,变量字节x、y和常量字符空间“”通过采用ASCII值在int中进行隐式转换。 x和y将保持不变,其中空格的值为32,因此它在屏幕上打印的只是J

有人能解释一下这个代码中的数学运算结果是35吗

public class Main {

    public static void main(String[] args) {
        byte x = 1;
        byte y = 2;
        System.out.println(x + ' ' + y);
}}

基本上,变量
字节
x、y和常量
字符
空间“”通过采用ASCII值在
int
中进行隐式转换。

x和y将保持不变,其中空格的值为32,因此它在屏幕上打印的只是Java中用于字符文本的单引号的和
1+32+2

,因此
'
是空格字符。字符的处理方式类似于以ASCII值为值的数字。空格的ASCII值为32。和1+32+2=35。

好的,经过大量的播放和进一步的研究,我发现“”将ascii字符值添加到x和y的值中

表达式:

x + ' ' + y
计算为(因为
+
是左关联的):

属于以下类型:

(byte + char) + byte
当您添加两个数值表达式时,操作数将进行二进制数值升级,以使其与加法兼容:在
字节
s和
字符
s的情况下,两个操作数都将加宽到
int
,并进行相加;结果是一个
int

   (byte + char) + byte
                            (apply binary numeric promotion to operands in bracket)
=  (int  + int)  + byte
                            (add the ints in the bracket)
=       int      + byte
                            (apply binary numeric promotion to operands)
=       int      + int
                            (add the ints)
=               int
因此:


只需将
'
替换为
'
。这些是以不同的方式添加的,而不是您认为的空间是ASCII 32。32+3等于35。这里的术语有点偏离。实际情况是,根据JLS中列出的规则,Java将两个
字节提升为
int
,而
char
转换为
int
。所以我们这里有一个普通的
int
加法。对,我实际上是想说“int”代表char,但我很快发布了答案。刚刚调整好,投票支持你。谢谢。“通过获取他们的ASCII值”是不准确的,因为
char
支持ASCII范围以外的值。
   (byte + char) + byte
                            (apply binary numeric promotion to operands in bracket)
=  (int  + int)  + byte
                            (add the ints in the bracket)
=       int      + byte
                            (apply binary numeric promotion to operands)
=       int      + int
                            (add the ints)
=               int
  (      x +       ' ') + y
= ((int) x + (int) ' ') + y
= (      1 +       32 ) + y
=        33             + y
=  (int) 33             + (int) y
=        33             + 2

=                      35