Friday, 7 June 2013

One question by a user on Java pass by reference

Hi

Was just going through one of the blogs where there was confusion on pass by value and pass by reference, i found a interesting problem posted by one of the user.

I guess he wanted to interchange values of 2 Objects using a temp Object.

This was his program

http://javapapers.com/core-java/java-pass-by-value-and-pass-by-reference/

hello guys, i am above Anonymous
i hope this will help more for your confusion.
just a simple example
public class point
{
int x,y;
public void tricky(Point arg1, Point arg2)
{
arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
public static void main(String [] args)
{
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
line 1:System.out.println(“X: ” + pnt1.x + ” Y: ” +pnt1.y);
line 2:System.out.println(“X: ” + pnt2.x + ” Y: ” +pnt2.y);
System.out.println(” “);
tricky(pnt1,pnt2);
line 3:System.out.println(“X: ” + pnt1.x + ” Y:” + pnt1.y);
line 4:System.out.println(“X: ” + pnt2.x + ” Y: ” +pnt2.y);
}
}
just think there is a pass by reference in java. the output at line 4 will be 100 and 100 but it gives 0 and 0. so there is no pass by reference in java.

X: 0 Y: 0
X: 0 Y: 0

X: 100 Y: 100
X: 0 Y: 0



import java.awt.Point;

public class point {

    int x;
    int y;

    public static void tricky(Point arg1, Point arg2) {
        arg1.x = 100;
        arg1.y = 100;
        Point temp = arg1;
        arg1 = arg2;
        arg2 = temp;
    }

    public static void tricky1(Point arg1, Point arg2) {
        arg1.x = 100;
        arg1.y = 100;
        Point temp = new Point(arg1.x, arg1.y);
        System.out.println("temp :: X: "+ temp.x + " Y: " +temp.y);
        arg1.x = arg2.x;
        arg1.y = arg2.y;
        arg2.x = temp.x;
        arg2.y = temp.y;
    }

    public static void main(String [] args) {
        Point pnt1 = new Point(0,0);
        Point pnt2 = new Point(0,0);
        System.out.println("X: "+ pnt1.x + " Y: " +pnt1.y);
        System.out.println("X: "+ pnt2.x + " Y: " +pnt2.y);
        System.out.println(" The users wrong way of pass by reference");
        tricky(pnt1,pnt2);
        System.out.println("X: "+ pnt1.x + " Y: " +pnt1.y);
        System.out.println("X: "+ pnt2.x + " Y: " +pnt2.y);
        System.out.println(" My solution to the problem pass by reference");
        tricky1(pnt1,pnt2);
        System.out.println("X: "+ pnt1.x + " Y: " +pnt1.y);
        System.out.println("X: "+ pnt2.x + " Y: " +pnt2.y);
    }
}

> java point

X: 0 Y: 0
X: 0 Y: 0
 The users wrong way of pass by reference
X: 100 Y: 100
X: 0 Y: 0
 My solution to the problem pass by reference
temp :: X: 100 Y: 100
X: 0 Y: 0
X: 100 Y: 100