2

我正在学习java并每天练习它,我编写了以下代码并想知道输出

class test
{
public static void main(String args[])
{
System.out.println(1+2+ " = " +10+2);
}
}

这里的输出是3=102,并且想知道以下“一旦在 System out 语句中遇到字符串,Java 就会开始将所有内容视为字符串”

谁能解释一下?我很困惑为什么它接受它作为字符串?

4

4 回答 4

6

Java 解析程序文本而不考虑表达式的类型。作为动机,考虑它们是否是在类中的方法之后编写的字段。因此,由于字符串连接和加法共享相同的运算符,我们有

1+2+ " = " +10+2

相当于

((((1+2)+ " = ") +10)+2)

折叠常数,我们有

(((3+ " = ") +10)+2)
(("3 = " +10)+2)
("3 = 10"+2)
"3 = 102"
于 2012-12-26T13:07:03.077 回答
1

+with String 成为字符串连接运算符,而不是加法运算符。

1 + 2 + 10 + 2将等于 15 作为简单加法,而
1 + 2 + "+" + 10 + 2将被视为
1.1 + 2输出将是 3,因为它是简单加法
2.3 + = (String) 输出将是 3=因为它是字符串连接
3.3= (String) + 10 + 2将是字符串连接而不是简单加法,因此输出将是3=102

于 2012-12-26T13:06:57.273 回答
1

“一旦在 System.out 语句中遇到字符串,Java 就会开始将所有内容视为字符串”

这是完全错误的。System.out是类的静态实例PrintStream。PrintStream 具有该println()方法的许多重载版本,您的示例中的一个接受String作为参数。您正在使用+ 运算符,它用于连接字符串,除非操作数都是数字。

System.out.println(3+5+"."); // println(String) is invoked.
System.out.println(3+5); // println(int) is invoked.
于 2012-12-26T13:08:17.820 回答
0
  (1+2) -- two integres additoin will result int 3
  (3 +  " = ") -- this will result int + String = String (concatination)
  ("3=") -- String + any thing (data type) will result String 
于 2012-12-26T13:07:26.767 回答