In the code below, if the string "Mult"
comes before the test1(4)
method call, why does the method output before the string? And why does it bounce form outputting the first part of the method, then leaves the method to output the string, then returns to the method to output the method's return value?
code:
public class Scratch{
public static void main(String[] args){
System.out.println("Mult:" + test1(4));
}
public static int test1(int n){
System.out.println("N:" + n);
return n*2;
}
}
Output:
N:4
Mult:8
In the code below, if the string "Mult" comes before the test1(4) method call, why does the method output before the string?
Because you're calling the method before you're calling System.out.println
with the "Mult:" part.
Basically, your code is equivalent to:
public static void main(String[] args){
int tmp = test1(4); // This prints N:4
System.out.println("Mult:" + tmp);
}
If you think about it, the test1
method has to be completed before the string concatenation can occur (otherwise we can't know what the right hand side of the concatenation operator is), and the string concatenation has to occur before the System.out.println
call can occur (otherwise we can't know what we're going to print). Make sense/
See more on this question at Stackoverflow