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

2.24 Integer Swapping With XOR

Juppies 2 by Dr Heinz M. Kabutz

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

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.