-5

This is the code I can't understand why v.i take 20! The result of this code is:

15 0
20  

Code:

class Value {
   public int i = 15;
}

class tes {
   public static void main(String argv[]) {
      tes t = new tes();
      t.first();
   }

   public void first() /* methode first */
   {
      int i = 5;
      Value v = new Value(); /* appel au classe Value */
      v.i = 25;
      second(v, i);
      System.out.println(v.i);
   } /* here it appears 20 ????? */

   public void second(Value v, int i) {
      i = 0;
      v.i = 20;
      Value val = new Value();
      v = val;
      System.out.println(v.i + " " + i);
   }
} /* it appears 15 0 i understand this */
Pshemo
  • 113,402
  • 22
  • 170
  • 242

3 Answers3

2

It's because in Java you pass a reference to an object by value. You can't change where this reference points to. You think you are changing what external v from first() points to inside of second(), but that's not the case. Effectively in the function signature of second() you are just declaring a variable v which initially points to passed value. You are changing that variable, not the external reference.

However when you assign to v.i it does have effect and updates its value. 20 is a correct result.

Make all arguments final, compile and look at the errors. This will provide a good insight.

This might explain it better than me: Is Java "pass-by-reference" or "pass-by-value"?.

Community
  • 1
  • 1
yǝsʞǝla
  • 15,379
  • 1
  • 39
  • 63
0

Step through your code carefully:

v.i = 20;  //Okay, pretty straightforward

Then you call:

Value val = new Value();  //Think about what val.i is

Now when you call this, v is pointing at the same object that val is pointing at:

v = val;

What's the value of i in that object?

musical_coder
  • 3,870
  • 3
  • 13
  • 18
0

v=val v is only a reference of val, not the original v.

v-->i=25

Then in method second

v-->i=20

Value val = new Value(); 

allocate a new memory space for val

now

v-->val.i = 15

after this, you can modify v.i as much as you want without affect the original data stored in v.i .

Josan
  • 610
  • 1
  • 5
  • 25