Running on Java 17+35-2724 (Preview)
Home of The JavaSpecialists' Newsletter

2.20 The Goat, The Wolf and The Cabbage (Swapping Integer Values)

Juppies 2 by Dr Heinz M. Kabutz

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 ...

Comments

When you load these comments, you'll be connected to Disqus. Privacy Statement.

Table of Contents

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.



About the Author

Heinz Kabutz Java Conference Speaker

Java Champion, author of the Javaspecialists Newsletter, conference speaking regular... About Heinz

Superpack 21

Superpack 21 Our entire Java Specialists Training in one huge bundle more...

Free Java Course

Free Juppies 2 Course
Juppies 2 - a course for complete beginners more...

Free Java Book

Dynamic Proxies in Java Book
Java Training

We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations.

Java Consulting

We can help make your Java application run faster and trouble-shoot concurrency and performance bugs...

Java Emergency?

If your system is down, we will review it for 15 minutes and give you our findings for just 1 € without any obligation.