The main objective of this post is to explain the correct method of comparing the strings in Java.

Can you answer the following quiz?

 * QUIZ: Guess output of the following code snippet:

String osName = System.getProperty(“osName”);

if (osName.equals(“Windows”)) {

       System.out.println(“You’re using Windows”);

}

 

For now, let write down your answer on paper. I will let you know the correct answer at the end of this post.

Friends, why I want you to answer the quiz above? Well, it’s because I’m going to share a tip about Strings comparison today.

* Why Strings comparison? It sounds very simple, but do you know that you have to compare Strings in every coding day of your entire life? Unless you die or you don’t coding any more, comparing Strings is your day-to-day chore, like you eat and drink.

I want to tell you about the comparison of a String variable against a String constant as shown in the code snippet above:

String osName = System.getProperty(“osName”);

if (osName.equals(“Windows”)) {

       // do something possibly on Windows

}

What if the variable osName gets null value?

Oops, a NullPointerException is thrown and the program stops. And you’re fired!

I recommend swapping the variable and the constant to avoid the potential NullPointerException. Hence the modified code:

if (“Windows”.equals(osName)) {

       // do something possibly on Windows

}

Now, with this simple modification, there’s definitely no NullPointerException even if the variableosName is null. Why?

It’s because I placed the String constant first (and a constant is always not null), so the if statement will return false in case the variable is null. The code is safer now.

Wow, that’s simply amazing, right?

 

So today, just remember always putting the String constant first in a Strings comparison. This is a really simple trick but can save your entire life!

Advertisements