Whilst the integer swap with plus and minus works, we can do it in an even cooler way. I've written a course called Bits and Bytes that shows how to code at a very low level in Java. Heartily recommended to help understand bitwise arithmetic in Java.
Instead of the confusing plus and minus, we can simply swap two ints x and y like this:
x ^= y y ^= x x ^= y
We can run our application, which runs our tests and starts up the game.
(You might justifiably wonder when you will ever need this XOR swapping trick "in the real world". I have never used it, and I have also never seen code that used it. So what is the point? Unfortunately before you can get a chance to code "in the real world" you need to run the gauntlet of the job interview. Some unimaginative interviewers might lob this at you, being the only thing they remember from their CSC 101W class. Being able to effortlessly answer: "Oh, I'd just XOR the two variables with each other a few times." might get you the job you are after. And once you have that job, you can be that person who throws it at the next hopeful programmer trying to enter the realm of the employed programmer." A temporary variable is not a big deal. Java will anyway optimize the code well. It is better to write clear obvious code than to use obscure tricks to make us look clever.)
We hope you enjoyed this tutorial. If you did, you will also enjoy our courses. We suggest you start with Extreme Java - Advanced Java, followed by Extreme Java - Concurrency Performance for Java 8.
We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations.
We can help make your Java application run faster and trouble-shoot concurrency and performance bugs...