Cannot understand why this Java program produces such output -


here code :

class value {     public int = 15; } public class test {     public static void main(string argv[])     {         test t = new test();         t.first();     }     public void first()     {         int = 5;         value v = new value();         v.i = 25;         second(v, i);         system.out.println(v.i);     }     public void second(value v, int i)     {         = 0;         v.i = 20;         value val = new value();         v =  val;         system.out.println(v.i + " " + i);     } } 

i cannot understand why code prints

15 0 20 

on console.

why not

15 0 15 

?

everything in java passed value. in first method

public void first() {     int = 5;     value v = new value();     v.i = 25;     second(v, i);     system.out.println(v.i); } 

you pass value of reference stored in v (which points value object i field value 15) second.

public void second(value v, int i) {     = 0;     v.i = 20;     value val = new value();     v =  val;     system.out.println(v.i + " " + i); } 

it dereferences reference value find value object , changes i field value 20. create new value object i field value initialized 15. that's you're printing

15 0 

the method returns , first prints value of object local variable v referencing, ie.

20 

Comments

Popular posts from this blog

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -

python 3.x - Mapping specific letters onto a list of words -