As I have read online that Java is pass by value and a general swap function won't swap the two values. I also read that it's not possible to swap the values of primitive types. I am wondering why the following program works and displays different valies after swap ?
public class swapMe { public static void main(String[] args) { int x = 10 , y = 20; System.out.println("Before"); System.out.println("First number = " + x); System.out.println("Second number = " + y); int temp = x; x = y; y = temp; System.out.println("After"); System.out.println("First number = " + x); System.out.println("Second number = " + y); } } Is it like somewhere, the original values of x = 10 and y = 20 are still stored somewhere and the swapped values displayed are not correct? Please advise. Thanks
xstored intempafterint temp = x;executes. And so on. They aren't "somewhere", you yourself told compiler exactly where they should be.