How can i change swap the values of i,j
in swap2()
function:
enter code here public class pass_by_ref {
public static void swap(Integer i, Integer j) //this will not change i j values in main
{
Integer temp = new Integer(i);
i = j;
j = temp;
}
public static void swap2(Integer i, Integer j)
{
i = 20; //as i am setting i value to 20 why isn't it reflected in main and same for j
j = 10;
}
public static void main (String[] args) throws java.lang.Exception
{
Integer i = new Integer(10);
Integer j = new Integer(20);
swap(i, j);
System.out.println("i = " + i + ", j = " + j);
swap2(i, j);
System.out.println("i = " + i + ", j = " + j);
}
}
Outputs:
i=10,j=20
i=10,j=20;
I think that Integer i=new Integer(10)
creates an object i
with value 10,so when i write i=20;j=10
in swap2()
i am setting there values!..so why isn't it working
i know that swap()
will not change i,j
values but why isn't swap2()
not working?
Well what change to make in swap2()
so that the values are swapped.