Does Java have something like C#'s ref and out keywords?

后端 未结 7 1511
陌清茗
陌清茗 2020-11-27 03:31

Something like the following:

ref example:

void changeString(ref String str) {
    str = \"def\";
}

void main() {
    String abc = \"abc\";
    chan         


        
7条回答
  •  一生所求
    2020-11-27 03:55

    Java passes parameters by value and doesn't have any mechanism to allow pass-by-reference. That means that whenever a parameter is passed, its value is copied into the stack frame handling the call.

    The term value as I use it here needs a little clarification. In Java we have two kinds of variables - primitives and objects. A value of a primitive is the primitive itself, and the value of an object is its reference (and not the state of the object being referenced). Therefore, any change to the value inside the method will only change the copy of the value in the stack, and will not be seen by the caller. For example, there isn't any way to implement a real swap method, that receives two references and swaps them (not their content!).

提交回复
热议问题