Java – Compare Strings

During the old Java days, the String object was a object to store a string of characters. Those days to compare Strings in Java, one would have to break down the characters in the String and compare them character by character.

Of course fast forward to the time now, one can just use the String methods to accomplish this. All thanks to the guys behind Java. Now how do we compare it now in Java? We would use Java 6 for this.

Why Choose Java Language

The common way people use to compare Strings is the

String.equals(); or the String.equalsIgnoreCase();

package com.Test;

public class TestString {

  public static void main(String... args) {

  // The 2 strings that we will test
  String testA = "Welcome";
  String testB = "Bye";

  // The additional String which is set to null
  String testC = null;

  if (testA.equals(testB))
    System.out.println("It is the same");
  else
    System.out.println("It is different");

  // Test it when testC is assigned to testA

  testA = testC;
  if (testA.equals(testB))
    System.out.println("Not same");

  System.exit(0);
  }

}

The above is the example of how to compare two Strings using equals. If you were to run the above code, a runtime error would occurupon running this application. How could this happen?

Reason is due to this syntax!


testA = testC;
if (testA.equals(testB))
  System.out.println("Not same");

testA was null during the comparison. Due to this, a null pointer exception would be thrown. Before this, this was how it was checked when TechieDan was doing coding many years back.


if (testA != null && testA.equals(testB))
  System.out.println("Not same");

By doing so, we have eliminated the problem regarding the null pointer exception. Somehow Java has evolved and instead of writing long codes to solve this issue, so why not we try importing a library to help with the solution.

We could use Commons Lang 2.6 (as of time of writing) which we could download at this page.
Commons Lang Download Page

Of course by including this lib into a project, one can now look at the wonders of comparison between Strings.

Now one can just write something like this.


if (StringUtils.equals(testA, testB))
  System.out.println("Not same");

It is that simple. By importing the library to one’s project, it negates off the null part and will not throw a null pointer exception if it was caught. If one is developing for a big project, this should be the standard of doing String comparisons.

Leave a Reply