1

What I am trying to do here is to swap two objects inside a method and outside the method. While I try to do it in a seperate method, the objects are NOT swapped and while done within the method, they are swapped. I dont understand what I am missing here. Here is the code snippet.

public class Swap {
    public static void main(String args[]) {
        Swap s = new Swap();
        s.testSwap();
    }   
    private void testSwap(){
        Animal a1 = new Animal("Lion");
        Animal a2 = new Animal("Crocodile");
        System.out.println("Before Swap:- a1:" + a1 + "; a2:" + a2);
        swapObjects(a1, a2);
        System.out.println("After Swap outside the method:- a1:" + a1 + "; a2:" + a2);
        Animal temp = new Animal("");
        temp = a1;
        a1 = a2;
        a2 = temp;
        System.out.println("After Swap within the method:- a1:" + a1 + "; a2:" + a2);
    } 
    public void swapObjects(Animal a1, Animal a2) {
        Animal temp = new Animal("");
        temp = a1;
        a1 = a2;
        a2 = temp;
    }
}

class Animal {
    String name;
    public Animal(String name) {
        this.name = name;
    }
    public String toString() {
        return name;
    }
}
Vinoth M
  • 5
  • 2

0 Answers0