假设我有一个方法:
public static int square(int x) {
System.out.print(5);
return x*x;
}
Run Code Online (Sandbox Code Playgroud)
我在main方法中调用此方法如下:
System.out.print("The square of the number "+7+" is "+square(7));
Run Code Online (Sandbox Code Playgroud)
我期待输出
The square of the number 7 is 549
Run Code Online (Sandbox Code Playgroud)
但是,实际输出是
5The square of the number 7 is 49
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
Cla*_*diu 10
调用函数时,在调用函数之前首先计算所有参数.
因此"The square of the number "+7+" is "+square(7)在System.out.print打印它之前进行评估.
因此square(7)被调用,然后调用System.out.print(5) 第一 -调用之前System.out.print.
后square(7)返回图49,字符串计算结果为"The square of the number 7 is 49",然后把它打印出来.
为了使它更加明确,就像你这样做:
String toPrint = "The square of the number "+7+" is "+square(7);
System.out.print(toPrint);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
105 次 |
| 最近记录: |