Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass by value/reference, what?

This program gives 6 as output, but when I uncomment the line 9, output is 5. Why? I think b.a shouldn't change, should remain 5 in main.

1  class C1{
2      int a=5;

3      public static void main(String args[]){
4          C1 b=new C1();
5          m1(b);
6          System.out.println(b.a);
7      }

8      static void m1(C1 c){
9          //c=new C1();
10         c.a=6;
11    }
12 }
like image 684
Naman Avatar asked Apr 24 '12 14:04

Naman


2 Answers

When you pass object in Java they are passed as reference meaning object referenced by b in main method and c as argument in method m1, they both point to the same object, hence when you change the value to 6 it gets reflected in main method.

Now when you try to do c = new C1(); then you made c to point to a different object but b is still pointing to the object which you created in your main method hence the updated value 6 is not visible in main method and you get 5.

like image 168
mprabhat Avatar answered Oct 05 '22 20:10

mprabhat


You're passing to your method m1 a copy of a reference to an Object of type C1.

If you uncomment the line, you're taking that reference and pointing it somewhere else (not that the original reference is still pointing at the first object), so, when you print the value of b, you're printing the value of the original object, that you didn't change.

This question has some very good answers to it, and you should really give it a look.

Is Java "pass-by-reference" or "pass-by-value"?

like image 27
pcalcao Avatar answered Oct 05 '22 18:10

pcalcao