假设我有一个方法:
public static int square(int x) {
System.out.print(5);
return x*x;
}
我在main方法中调用此方法如下:
System.out.print("The square of the number "+7+" is "+square(7));
我希望输出为
The square of the number 7 is 549
但是,实际输出是
5The square of the number 7 is 49
为什么会这样?
答案 0 :(得分: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);
答案 1 :(得分:4)
行System.out.print("The square of the number "+7+" is "+square(7));
编译为:
System.out.print(new StringBuilder()
.append("The square of the number ")
.append(7)
.append(" is ")
.append(square(7))
.toString());
结合您的方法square()
,如果您使用调试器逐步执行代码,您将看到的方法调用序列是:
new StringBuilder()
append("The square of the number ")
append(7)
append(" is ")
square(7)
print(5)
append(49) <-- value returned by square
toString()
print("The square of the number 7 is 49") <-- value returned by toString
如您所见,它会调用print(5)
,然后 print("The square of the number 7 is 49")
,从而产生输出:
5The square of the number 7 is 49
答案 2 :(得分:-2)
您有两个选项,要么从方法返回要打印的值,要么只在方法内部执行System.out.print。
您真的想从5
打印square
吗?