In short: Java has pointers and is strictly pass-by-value.

如果再說詳細一點, Java 中的型態可以分為 primitive data type (Java 快速導覽 - 基本資料型態和參考變數) 跟其它,其它型態在 Java 中全部都是 Object

  1. Primitive data types are passed by value
  2. Object references are passed by value

以下擷取 Java is Pass by Value and Not Pass by Reference 的部分範例程式碼:

public class Main
{
     public static void main(String[] args){
          Foo f = new Foo("f");
          changeReference(f); // It won't change the reference! 如果是 C++ 的 pass-by-reference 的行為,這個 function 的確會 change reference
          modifyReference(f); // It will change the object that the reference variable "f" refers to!
     }
     public static void changeReference(Foo a) {
          Foo b = new Foo("b");
          a = b;
     }
     public static void modifyReference(Foo c) {
          c.setAttribute("c");
     }
}

Ref:

  1. Java is Pass by Value and Not Pass by Reference
  2. Java is Pass-by-Value, Dammit!

Comments

comments powered by Disqus
Copyright © 2013 Andro Chen
Powered by Logdown and Greyshade
Favicon from The Noun Project