Why there is no way to pass by reference in java

后端 未结 3 579
滥情空心
滥情空心 2021-01-29 13:56

I guess java does not have the option \"pass by reference\" .But why ? Because sometimes it is very needed.

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-29 14:30

    In Java no matter what type of argument you pass the corresponding parameter (primitive variable or object reference) will get a copy of that data, which is exactly how pass-by-value (i.e. copy-by-value) works. In Java, if a calling method passes a reference of an object as an argument to the called method then the passed in reference gets copied first and then passed to the called method. Both the original reference that was passed-in and the copied reference will be pointing to the same object. So no matter which reference you use, you will be always modifying the same original object, which is how the pass-by-reference works as well.

提交回复
热议问题