Reputation: 209
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?
Upvotes: 5
Views: 114
Reputation: 159086
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
Upvotes: 4
Reputation: 229321
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);
Upvotes: 10
Reputation: 27476
You have two options, either you return the value you want to print from the method, or you just do System.out.print inside the method.
Do you really want to print 5
from square
?
Upvotes: -2