returning a value from a method to another method

前端 未结 8 583
时光取名叫无心
时光取名叫无心 2021-01-19 14:42

Can somebody tell me why the value returned is 3 and not 8. Doesn\'t the return x statement from the addFive method change the value of x

相关标签:
8条回答
  • 2021-01-19 15:13

    when you call a method in java and you don't assign for any variable, the changes will happen in the method call, after that this value will be lost and go back to the value that you assign. to see the result you should do that System.out.println(addFive(x)); but if you want to change the value of x you have to assign x = addFive(x);

    0 讨论(0)
  • 2021-01-19 15:13

    The value in the main function is completely different from the value in the addFive(int x ) function. You send an x from main to addFive(int x) method.

    JVM makes a copy of x and send it to addFive(int x) method. Then x changes in the addFive(int x) method. But the x in main() method remains unchanged.

    If you want to get the changed value returned by addFive(int x) from main method you can do the following -

    int returnedValueFromAddFive = addFive(x)  
    

    Hope it will help.
    Thanks a lot.

    0 讨论(0)
提交回复
热议问题