-1

I have two classes. The first class call to call method(with parameter) that is inside in second class. I want to know when parameter pass , it copy to MyClass ref or it pass by reference.

public class NewClass 
{
    public static void main(String[] args)
    {
        MyClass obj = new MyClass();
        obj.val = 1;
        obj.call(obj);
        System.out.println(obj.val);
    }
}


public class MyClass 
{
    public int val;
    public void call(MyClass ref)
    {
        ref.val++;
    }
}

The output is 2. My understanding is it is pass by refernece. Please confirm my answer. Thank you very much.

T8Z
  • 691
  • 7
  • 17

1 Answers1

2

Java always passes by values. Your example is misleading.

If it passed by references, if you did:

public void call(MyClass ref) { ref = new MyClass(); }

then ref would change; and it doesn't.

What you pass is a value to an object reference.

fge
  • 119,121
  • 33
  • 254
  • 329
  • Thank you for your explanation. But my understanding is Passing arguments by value means that a copy of the argument is passed to the method. Is it right for this problem. – T8Z Mar 24 '14 at 16:41
  • Yes, it is the same. Note that an object reference is just an address. You don't push the _full_ object into the stack. You can think of it as a "pointer" if you like. – fge Mar 24 '14 at 16:45
  • A copy of the *reference* is passed to the method. The name "reference" is distressingly misleading here. Be aware that `MyClass ref` is NOT the whole object itself, but only some sort of "handle", or a "remote control"... EDIT @fge The name "pointer" also came to my mind, but it's an even more overloaded term than "reference" ;-) – Marco13 Mar 24 '14 at 16:46