Why does java use both pass-by-value and pass-by-r

2019-07-29 07:02发布

问题:

Possible Duplicate:
Is Java “pass-by-reference”?

Maybe I'm missing something...but I can't really understand why Java uses both the pass-by-value and pass-by-reference. Why not using only one paradigm?

回答1:

It doesn't. Java is purely pass-by-value. The value passed when you're dealing with an object is an object reference, but that has nothing to do with "pass by reference."

Pass-by-reference means that a function can be passed a variable and change the contents of that variable in the calling function. That does not exist in Java.

So for instance:

void foo() {
    int a;

    a = 42;
    bar(a);
    System.out.println(a); // Will ALWAYS be 42
}

void bar(int b) {
    b = 67;
}

Contrast with C++, which does have pass-by-reference:

// C++ code
void foo() {
    int a;

    a = 42;
    bar(a);
    cout << a; // 67?!
}
void bar(int& a) { // <== Note the &
    a = 67;
}

Java has no equivalent of the & in C++ (or out / ref in C#).

You're probably thinking of object references, which is a completely separate use of the word "reference" than the "reference" in pass-by-reference. Let's look at an example with objects:

void foo() {
    Object o1, o2;

    o1 = new Object();
    o2 = o1;
    bar(o1);
    System.out.println(o1 == o2); // Will ALWAYS be true
}

void bar(Object o) {
    o = new Object();
}

If Java had pass-by-reference (and we'd used it to pass the object variable to bar), the == in foo would be false. But it isn't, and there is no way to make it so.

The object reference allows you to change the state of the object passed into the function, but you cannot change the variable that contained it in the calling function.



回答2:

Java is always "Pass By Value". So primitives as well as Object's (reference) both are passed by value.

Edit

Yeah, objects are not passed directly, we always refer them with their reference. So Object's reference is passed by value.