Running on Java 21-ea+14-1161 (Preview)
Home of The JavaSpecialists' Newsletter

2.23 Fixing the Integer Swapping Code

Juppies 2 by Dr Heinz M. Kabutz

We were too much in a hurry to enter the code, taking shortcuts and not being careful about each step. This happens frequently when we are overconfident. The first line with indexes[i] += indexes[swap] is correct. However, the second line is wrong. In our example, we wrote y = x - y, but that is not equivalent to y -= x. Our code should have been indexes[swap] = indexes[i] - indexes[swap].

We run the test and it passes this time. Fantastic! Keep the test green to keep the code clean. We have also improved our unit test to confirm that the numbers in the shuffled index are exactly the same as before.

We commit our changes to our local repository, describing our improvements, such as better tests, improved swapping algorithm and having set up NetBeans to automatically run our unit tests every time we run our game. We could submit our changes individually as separate commits or as one, but we should take care that every commit by itself does not break the build.


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 '23

Superpack '23 Our entire Java Specialists Training in one huge bundle 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.