When going for a job interview for your first Java job, there is a non-zero chance that you will be asked some coding questions. For example: "How do we swap two int values without using a temporary variable?"
The problem with that particular question is that the answer that they are looking for is quite obscure and probably not the way that I would code. I want my code to be easily understandable. I don't want someone reading my code to have to think too much. You might argue this to your interviewer, and they might be impressed with your conviction, but you also might not get the job.
There are two main tricks used to swap two int values. Here is the first using addition and subtraction. Say we have x = 4 and y = 7. The trick is to start by making x = x + y (11). We then set y = x - y (11 - 7 == 4) and then set x = x - y (11 - 4 == 7). Swap done. The code before was:
int tmp = indexes[i]; indexes[i] = indexes[swap]; indexes[swap] = tmp;
We change this to:
indexes[i] += indexes[swap]; indexes[swap] -= indexes[i]; indexes[i] -= indexes[swap];
Let's test our code next ...
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...