Where does return value go in java if no variable assigned to accept it?

后端 未结 4 515
南方客
南方客 2021-01-07 03:17

Let\'s say a method returns some value, but when I call it, I don\'t assign any variable to accept this RV. Then where does it go? Will GC collect it? Would it be a problem

4条回答
  •  借酒劲吻你
    2021-01-07 03:26

    There's nothing that special about a return value over a local variable, consider:

    public Object example {
      Object a = new Object();
      return new Object();
    }
    

    Then if I briefly explain how return values work:

    When a method starts a new "stack-frame" is pushed on to the stack. It is an area of memory that includes parameter and local variable storage including the return value. It also knows where to return to.

    When the method executes, new objects are created on the heap and only pointers to them exist in the stack.

    After the code for the method has been run the value of a non-void return method is passed back to the calling method and stored in it's stack frame.

    If a non-void return method's value isn't required by the caller, then it will share the same fate as any other local variable in that stack frame. And that is it's value is no longer used. If that value was an object, then garbage collection is already aware of it and is now able to ascertain that it is not referenced and can be collected.

提交回复
热议问题