有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么一个整数和一个数字连在一起会产生一个字符串?

我正在进行AP Comp Sci实践测试,发现以下问题:

以下内容的输出是什么:

System.out.println("1" + new Integer(2) + 3);

答案是

123,

我感到困惑,因为new Integer(2)没有被转换成字符串,因此,如果两部分都是整数,为什么java编译器认为new Integer(2) + 3语句是字符串连接


共 (2) 个答案

  1. # 1 楼答案

    最初的问题是:

    System.out.println("1" + new Integer(2) + 3);
    

    为什么这给了我们“123”;我猜提问者的意思不是6或15

    让我们对此进行简化,并将新的整数位删除为其等效值:

    System.out.println("1" + 2 + 3);
    

    Java语言规范12给出了答案(4.2.2):

    The string concatenation operator + (§15.18.1), which, when given a String operand and an integral operand, will convert the integral operand to a String (the decimal form of a byte, short, int, or long operand, or the character of a char operand), and then produce a newly created String that is the concatenation of the two strings. https://docs.oracle.com/javase/specs/

    15.18.1节更加明确:

    The additive operators have the same precedence and are syntactically left-associative (they group left-to-right). If the type of either operand of a + operator is String, then the operation is string concatenation. https://docs.oracle.com/javase/specs/

    因此,由于运算符+在这两种情况下都使用,它从左到右求值,无论是串联还是加法,如15.18.1所述,以及其他回答者所述。第一个操作数“1”是字符串,第二个操作数是整数2,因此根据上述规则,整数2被转换为字符串“2”,加号被解释为串联,得到一个字符串“12”。然后它有一个字符串“12”和一个整数3,因此整数3根据上述规则进行转换,+再次被解释为串联,我们得到一个字符串“123”

    如果他们在2+3周围加了括号:

    System.out.println("1" + (2 + 3));
    

    显然,这将迫使首先评估2+3。它们都是整数,所以得到一个整数5。然后我们会有“1”+5,这是一个字符串加上一个整数,所以整数被转换成字符串“5”,它们被连接起来,得到“15”

    如果他们像这样改变了顺序:

    System.out.println(2 + 3 + "1");
    

    然后,2+3将首先按照从左到右的规则进行,因为它们都是整数,+将意味着加法,这将产生一个整数5。然后我们将有整数5和字符串“1”的运算符。根据上述规则,整数5被转换为字符串5,+被解释为串联,我们得到一个字符串“51”

    所有这些操作都可以归结为操作顺序,所有这些操作都是二进制的(一次只取两个),并且,当使用加号时,如果一个操作数是字符串,另一个操作数如果不是字符串,则被更改为字符串,加号被解释为串联,结果是字符串

  2. # 2 楼答案

    加法是左联想的。a+b+c==(a+b)+c