This occured while I was tackling a 'Cracking the Coding interview' question:
Write a function to swap a number in place (that is, without temporary variables)
I decided to write up my solution in Java (because I plan on using Java in my internship interviews.)
I came up with a solution that I was almost confident was the right answer (because I did it in one line):
public static void main(String args[]) {
int a = 5;
int b = 7;
a = b - a + (b = a);
System.out.println("a: " + a + " b: " + b);
}
Surely enough, this code executes the desired result. a == 7
and b == 5
.
Now here's the funny part.
This code won't run in C++ nor is this solution in the back of the book.
So my question is: Why exactly does my solution work? I am assuming Java does things differently than other languages?