Created
July 16, 2019 16:23
-
-
Save Kaushal28/036b3c268bbd95482ae344af0494fa40 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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