Isaac Nam Isaac Nam - 1 year ago 135
Java Question

Output of a swap function

I'm new to java and new to stackoverflow. Here is a code from my textbook:

public static void main(String[] args) {
Circle circle1 = new Circle(1);
Circle circle2 = new Circle(2);

swap1(circle1, circle2);
System.out.println("After swap1: circle1 = " +
circle1.radius + " circle2 = " + circle2.radius);

swap2(circle1, circle2);
System.out.println("After swap2: circle1 = " +
circle1.radius + " circle2 = " + circle2.radius);

public static void swap1(Circle x, Circle y) {
Circle temp = x;
x = y;
y = temp;

public static void swap2(Circle x, Circle y) {
double temp = x.radius;
x.radius = y.radius;
y.radius = temp;

class Circle {
double radius;

Circle(double newRadius) {
radius = newRadius;


The output reads as "After swap1: circle1 = 1.0 circle2 = 2.0"
"After swap2: circle1 = 2.0 circle2 = 1.0" My question is how does this work? Why isn't the first print statement the same as the second? Are you not allowed to swap two different objects? Thanks in advance.

Answer Source

In both functions you have the two object as parameter but you are not sending an object, you actually sending a memory reference of the object. If you change the object inside the function, that changes will be reflected after the function (swap2 example). In the swap1 you are only swaping the memory reference of the objects, that changes will not be reflected after the function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download