-1

is Java works based on Call by reference or call by value make me confusion?

class Point  {

    int x, y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

public class demo {

    public static void tricky(Point arg1, Point arg2)   {
        Point temp = arg1;
        arg1 = arg2;
        arg2 = temp;
    }

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

    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);
        tricky(pnt1,pnt2);
        System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
        System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
        tricky1(pnt1,pnt2);
        System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
        System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
    }
}  

I'm confused after first method(tricky) got executed i got expected result, but not after second method(tricky).

pezetem
  • 2,503
  • 2
  • 20
  • 38

1 Answers1

0

It is pass by value. This code:

public static void main(final String... args)
{
    String s = "foo";
    tryAndModify(s);
    System.out.println(s);
}

private static void tryAndModify(String s)
{
    s = "bar";
}

will print foo.

s is a reference to a String object, sure. But this is a value as a method call parameter. It is quite a separate concept to "pass by reference" like C++ has, for instance.

fge
  • 119,121
  • 33
  • 254
  • 329
  • @user902383 yes you will... I can change the example to use a `String` if you want – fge Mar 19 '14 at 11:23