Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class Car {
int number;
Car(int number) {
this.number = number;
}
void printNumber() {
System.out.println(this.number);
}
}
class WrapperCar {
Car c;
WrapperCar(Car c) {
this.c = c;
}
}
public class SwappingObjs {
static void swap(Car c1, Car c2) {
Car temp = c1;
c1 = c2;
c2 = temp;
}
static void swapCorrectly(WrapperCar wc1, WrapperCar wc2) {
Car temp = wc1.c;
wc1.c = wc2.c;
wc2.c = temp;
}
public static void main(String[] args) {
Car c1 = new Car(1);
Car c2 = new Car(2);
//This works as we are not passing the objects
// Car tmp = c1;
// c1 = c2;
// c2 = tmp;
//Passing doesn't work because java is pass by value and not reference
swap(c1, c2);
System.out.println(c1.number);
System.out.println(c2.number);
//Finally this will work
WrapperCar wc1 = new WrapperCar(c1);
WrapperCar wc2 = new WrapperCar(c2);
swapCorrectly(wc1, wc2);
System.out.println("Car1: " + wc1.c.number);
System.out.println("Car2: " + wc2.c.number);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment