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 }
When you pass object in Java they are passed as reference meaning object referenced by
binmainmethod andcas argument in methodm1, they both point to the same object, hence when you change the value to 6 it gets reflected inmainmethod.Now when you try to do
c = new C1();then you madecto point to a different object butbis still pointing to the object which you created in yourmainmethod hence the updated value 6 is not visible in main method and you get 5.