Java When outputting String and method return, why does method return output first? -


in code below, if string "mult" comes before test1(4) method call, why method output before string? , why bounce form outputting first part of method, leaves method output string, returns method output 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 

the first thing note when use + 2 operands 1 of 2 operands string, result of expression string.

therefore, in following method invocation expression

system.out.println("mult:" + test1(4)); 

you invoking printstream#println(string) since out variable of type printstream. note how method accepts single string argument. therefore, string has resolved string concatenation of

"mult:" + test1(4) 

for happen, test1(4) method has executed.

public static int test1(int n){     system.out.println("n:" + n);     return n*2; } 

this method again uses printstream#println(string) argument

"n:" + n 

this string concatenation produces string value

"n:4" 

for particular invocation. produced string value used argument println(..) method outputs program's standard output.

the method returns value 8, since 4 * 2 = 8.

that return value value of invoking 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 string value

"mult:8" 

that string used single argument println(..) method outputs program's standard output.


Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

c# - Unity IoC Lifetime per HttpRequest for UserStore -

I am trying to solve the error message 'incompatible ranks 0 and 1 in assignment' in a fortran 95 program. -