3

I know, in Java the parameters passing is made by value for primitive type and by reference for reference type (object). Why in the example below,that I think is a reference passing parameters, the object point is not modified after method swap?

public class Swap2 {

    public static void swap(Point p1, Point p2) {
        Point temp = p1;
        p1 = p2;
        p2 = temp;

        System.out.println("p1.x " + p1.x);
        System.out.println("p2.x " + p2.x);                                 
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        Point p1 = new Point(100,200);
        Point p2 = new Point(300,400);
        //System.out.println("p1=" + p1.toString());
        System.out.println("p1=" + p1);     
        System.out.println("p2=" + p2);
        swap( p1, p2 );
        System.out.println("p1.x " + p1.x);
        System.out.println("p1=" + p1);
        System.out.println("p2=" + p2);    
    }    
}
Tiny
  • 27,221
  • 105
  • 339
  • 599
Stefano Maglione
  • 3,946
  • 11
  • 49
  • 96

5 Answers5

5

Parameters in java are always passed by value, but in the case of objects, the passed value is the object's reference (pointer).

So your assignment has no effect outside of the function's scope, since you are just swapping the contents (values) of two local variables.

Marco Bolis
  • 1,222
  • 2
  • 15
  • 31
4

Java is always pass by values, doesn't matter whether it's primitives or reference passing.

You are passing copy of the Virtual Memory address of the reference to an object to that method. And in that method, You just reassigned the copied reference to another object.

Your code proves that java pass by value :)

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
0

Wrong - Java is always pass by value for both primitives and references types. Your misunderstanding is the root of your problem.

What's passed by value for object types is the reference, so you cannot modify it. You can modify the state of the object that the reference points to, but only if it's mutable.

The object is not passed; it lives out on the heap.

duffymo
  • 305,152
  • 44
  • 369
  • 561
0

As a few already pointed out - the references are values, and you just change the references. What you want to do is to change inside the objects. Then the swap method would work.

i.e.

p1.x = p2.x;
p1.y = p2.y;

and so on.

Bex
  • 2,905
  • 2
  • 33
  • 36
0

I've made an analogy in here, if it helps: blog.aaronshaw.net/2014/02/13/java-is-always-pass-by-value/

Aaron
  • 652
  • 4
  • 10