Java is pass-by-value, so is Python

  • All cited from Best description with different proof, by Xuan Luo
    • C++ is said to have both pass-by-reference (when a parameter is of a reference type, i.e. has a "&") and pass-by-value (otherwise).
    • Java's types are divided into primitive types and reference types. Java's primitive types (int, double, boolean, etc.) are easily mapped to primitive types in C++.
    • In Java, if you have a class Foo, there is also a non-primitive type called "Foo". What is this type equivalent to in C++? It is not the type "Foo" in C++, because that is an object type, where the lifetime of the object is tied to the lifetime of the variable (which has no equivalent in Java), and assignment between type "Foo" causes the contents of one object to be copied over into another object (which also has no general equivalent in Java). Rather, the type "Foo" in Java is equivalent to the type Foo * in C++ (a pointer-to-object type).
    • Basically, any piece of Java code involving type Foo can be converted into an equivalent C++ code involving Foo *, or vice versa, keeping the same structure of assignments, field access, and other key operations. The difference is that the "." operator in Java is equivalent to the "->" operator in C++.
    • JLS 4.3.1 defines "references" as "pointers to objects" or the null reference
    • Passing a "Foo" parameter in Java works exactly the same as passing a "Foo *" parameter in C++. In both cases, it works like the parameter is assigned (as if by assignment) the expression passed. In C++, we would say that a pointer to an object is passed, by value; so the same is true in Java.
    • Everything said above about Java also applies equally to Python: object lifetimes are not tied to the function in which they are created; you can assign one variable to another causing two variables to point to the same object with the same (shared) state; assigning a variable to point to a new object does not affect the object it used to point to.

Based on how it is used in C++, a good definition that is based solely on semantics is the following:

  • If you pass a variable to a function, if simple assignment (e.g. =) on the parameter inside a function has the same effect as if you performed simple assignment on the passed variable outside the function, it is pass-by-reference.
  • If you pass a variable to a function, if simple assignment (e.g. =) on the parameter inside a function has no effect on the passed variable outside the function, it is pass-by-value.
  • C, Go, Java, JavaScript, Objective-C, Python, Ruby and many similar languages are always pass-by-value. C++, C#, and PHP have both pass-by-value and pass-by-reference

results matching ""

    No results matching ""