Given:

System.out.println("5 + 2 = " + 3 + 4);
System.out.println("5 + 2 = " + (3 + 4));

What is the result?

A.

5 + 2 = 34
5 + 2 = 34

B.

5 + 2 + 3 + 4
5 + 2 = 7

C.

7 = 7
7 + 7

D.

5 + 2 = 34
5 + 2 = 7

题解

操作符「+」若其中一个操作数为字符串,那么它将会做字符串连接,否则为加法运算。

由于优先级的关系,题目第 1 行会等同:

System.out.println(("5 + 2 = " + 3) + 4);

因此「3」和「4」会被当作字符串进行连接。

若题目是写成:

System.out.println(5 + 2 + " = 3 + 4");

等同:

System.out.println((5 + 2) + " = 3 + 4");

因此会输出:

7 = 3 + 4