Home > Net >  How to solve change contents of variables having values from call by reference facility in Java?
How to solve change contents of variables having values from call by reference facility in Java?

Time:06-09

I had written the following code as follows:

class Numbers
{

    int temp,a1,b1;

    void swapping(){
        temp = a1;
        a1 = b1;
        b1 = temp;
        System.out.println("In numbers class value of a after swapping =" a1   " and that of b="   b1);
    }
}
public class Swap{

    public static void main(String[] args) {
        int a=2;
        int b=3;
        System.out.println("In swapping class value of a before swapping =" a   " and that of b="   b);

        Numbers num = new Numbers();        

        num.a1= a;
        num.b1= b;
        num.swapping();
        System.out.println("In swapping class value of a after swapping =" a   " and that of b="   b);
    }

}

Now the values of a1 and b1 in void swapping() are unchanged as per the dummy println statement just after the swapping operation is implemented on both a1 and b1 . This is the same as the values printed in the main function just before the swapping function was called . However the println statement in the main function after the function call shows the swapped values . Suppose instead of the swapped values some garbage value is stored due to some unforeseen abnormalities in Java compiler , then how to change that to whatever is desired?

CodePudding user response:

System.out.println("In swapping class value of a after swapping =" a   " and that of b="   b);

You are just printing a and b variables here. Because there is no re-assignment for a and b anywhere in swap class. Change your code to print num.a1 and num.b1 and you should see the values changed for num object

CodePudding user response:

The trick here is understanding that Java has two parallel digram of main method distinct from object

So code in separate scopes can share references to the same object. But code in separate scopes cannot share the very same primitive variable, they can only get a copy of the other's primitive variable's value.

You would see very different behavior if you had used Integer class rather than int primitive in all five places. You might want to play with that to master these concepts.

  • Related