Saturday, February 5, 2011

A tiny trick thanks to the autoboxing.

Today it will be short and tiny. The whole trick bases on the Java autoboxing feature. Let's say that we want to implement a method that checks whether a string that the passed reference points to, is evil. The first question that may pop up in your mind is when the string is evil? That mostly depends on you, in our example though, we will assume that it happens when it's equal to “666”. But wait, this article is not really about evilness. Let's go back to the way we should implement our method. The first important thing, is to check whether the reference is equal null. After that we can just invoke the equals() method inherited from the Object class and based on its result return true or false. A sample implementation could look like this:

public class StringTest {
static boolean isEvil(String evil) {
if(evil == null) {
return false;
}
return evil.equals("666");
}
}
But if we would like to get some advantage from the autoboxing feature in Java, we can easily get rid of the null check in our method. You probably ask why we can do that. It's simple – the null check is already done in the equals() method that the String class provides so why would we repeat it? To achieve the above, we have to force the “666” to be autoboxed and then invoke the equals() method on the new object against the passed reference. The following code shows the whole solution:

public class StringTest {
static boolean isEvilEnhanced(String evil) {
return "666".equals(evil);
}
}
It's shorter, still easily readable and what's more important, faster! (The autoboxing in the first example has to be done anyway, since the equals method takes a reference to the Object class)