Java transfer options

I know that in Java, parameters are passed by value for a primitive type and by reference for a reference type (object). Why in the example below, which, in my opinion, is a reference parameter of the transfer, the point of the object does not change after replacing the method?

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);    
    }    
}
+3
source share
5 answers

Java always goes through values , it doesn't matter if it is primitive or reference.

You pass a copy of the virtual memory address of the object reference for this method. And in this method, you simply reassigned the copied link to another object.

Your code proves that java passes by value :)

+4
source

java , ().

, , () .

+4

- Java , . - .

, , , . , , .

; .

0

, - , . , , - . .

.

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

..

0
0
source

All Articles