Java – Which Arguments Pass by Value and Which Pass by Reference?

calling-conventionsjava

I am starting to learn Java with the Java Trails tutorials offered by Oracle. I am in the section where it talks about passing arguments to methods The Java™ Tutorials: Passing Information to a Method or a Constructor.

It says that primitive types are passed by value, which makes sense to me. Right after that it says:

Reference data type parameters, such as objects, are also passed into
methods by value. This means that when the method returns, the
passed-in reference still references the same object as before.
However, the values of the object's fields can be changed in the
method, if they have the proper access level.

Now this doesn't make sense to me. If an object is passed by value, then changing the fields of that object will change the fields of the copy inside the method, not the original one.

When testing with the program below:

class Point {
    int x;
    int y;

    public static void movePoint(Point p, int x, int y) {
        p.x+=x;
        p.y+=y;
    }
}
class App {
    public static void main(String argv[]) {
        Point p1;

        p1 = new Point();
        p1.x = 2;
        p1.y = 3;

        p1.movePoint(p1,2,2);

        System.out.println("x = " + p1.x +  " y = " + p1.y);
    }
}

It worked as if the object was being passed by reference (it prints out x = 4 y = 5 after all).

So what exactly did Oracle mean in the passage above? Also, can anyone summarize what's passed by value and what's passed by reference in Java?

Best Answer

Java is pass by value. Think of it like a pointer language like C, the value of the pointer (memory address) is being passed, so you have a reference to the same object. Primitives aren't stored internally the same way as Objects, so when you pass a primitive's value, it's the content, not a pointer.

Related Topic