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

后端 未结 5 1021
Happy的楠姐
Happy的楠姐 2021-01-23 06:03

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

5条回答
  •  难免孤独
    2021-01-23 06:33

    When

    System.out.println("Mult:" + test1(4));
    

    is run, test1(4) must be evaluated before it can be System.out.println'd. So, the JVM will run the following:

    evalate result of test1(4) {
        print ("N:" + 4);
        return 2*4;
    }
    evalate result of "Mult:" + returnedValue {
        print("Multi:" + returnedValue);
    } 
    

    The JVM cannot print something before it knows its value. In this case, test1(4) get evaluated first so the JVM knows what to print out (the return value).

    You could also complete the task this way>>

    int result = test1(4); //This prints out 4 and evaluates to 8
    System.out.println("Mult: " + result); //This concats "Mult: " and 8 after converting it to of type String
    

提交回复
热议问题