Suppose I have a method:
public static int square(int x) {
System.out.print(5);
return x*x;
}
I call this method in the main method as follows:
System.out.print("The square of the number "+7+" is "+square(7));
I expect the output to be
The square of the number 7 is 549
However, the actual output is
5The square of the number 7 is 49
Why does this happen?
When you call a function, all the arguments get evaluated first before the function is called.
So "The square of the number "+7+" is "+square(7)
gets evaluated before the System.out.print
that prints it.
Thus square(7)
gets called, which then calls System.out.print(5)
first - before the calling System.out.print
.
After square(7)
returns 49, the string evaluates to "The square of the number 7 is 49"
, which then gets printed.
To make it even more explicit it's as if you did this:
String toPrint = "The square of the number "+7+" is "+square(7);
System.out.print(toPrint);
The line System.out.print("The square of the number "+7+" is "+square(7));
compiles to:
System.out.print(new StringBuilder()
.append("The square of the number ")
.append(7)
.append(" is ")
.append(square(7))
.toString());
Combined with your method square()
, the sequence of method calls you would see if you stepped through the code with a debugger is:
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
As you can see, it calls print(5)
, then print("The square of the number 7 is 49")
, resulting in the output:
5The square of the number 7 is 49
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With