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 f
The first thing to note is when you use the +
with two operands where one of the two operands is a String
, the result of the expression is a String
.
Therefore, in the following method invocation expression
System.out.println("Mult:" + test1(4));
you are invoking the PrintStream#println(String) since out
is a variable of type PrintStream
. Note how the method accepts a single String
argument. Therefore, the String
has to be resolved from the String
concatenation of
"Mult:" + test1(4)
For that to happen, the test1(4)
method has to be executed.
public static int test1(int n){
System.out.println("N:" + n);
return n*2;
}
This method again uses PrintStream#println(String)
but with the argument
"N:" + n
This is another String
concatenation that produces the String
value
"N:4"
for this particular invocation. The produced String
value is then used as an argument to the println(..)
method which outputs it to your program's standard output.
The method then returns the value 8
, since 4 * 2 = 8
.
That return value is the value of invoking the test1(4)
method. So
System.out.println("Mult:" + test1(4));
is equivalent to
System.out.println("Mult:" + 8);
Then String
concatenation occurs, transforming
"Mult:" + 8
into the String
value
"Mult:8"
That String
is then used as the single argument to the println(..)
method which outputs it to your program's standard output.