String

Java Compare Strings Example

Today we are going to focus on how you can compare Strings in Java. By comparing, in this case, we mean to check if their values are equal.

In the previous example, we talked generally about the Java String Class. We stated that Java lets you initialize a String like a primitive, and use the ‘+’ operator like you would in a primitive, but here used to concatenate Strings together.

The similarities stop here. A String is in no way a primitive type. It is a classic Java Object. So comparing a String is no different from comparing any other Java Object.

1. The ‘==’ operator

It is strongly (and correctly) advised that you should never use ‘==’ to compare any two Objects. Let’s see an example

Equals Operator

//Objects a and b are of the same non primitive type
if(a==b)
  System.out.println("The to objects are equal");

In the above example we are comparing two references, not objects. If the two references are equal, it simply means that they are pointing to the same Object instance. Consequently, a and b are equal, as they are exactly the same object.

But in most cases, you have two different discrete object of the same type that have equal contents. And it is the contents that matter in an equality check. This is where you use the equals method.

2. Java Compare Strings – Using equals

equals is a member of the Object class, so any class in Java can override it an create its own customized equality check.

Here is how you can use it in Strings:

Equals

String a = "Java is great!";
String b = "Java is great!";
if(a.equals(b))
    System.out.println("The strings are equal");

The output of the above is:

The strings are equal

Due to String pooling that we’ve talked about in the previous example, the ‘==’ operator also works:

Equals Operator

String a = "Java is great!";
String b = "Java is great!";
if(a == b)
    System.out.println("The strings are equal");

The output of the above is:

The strings are equal

That’s because literals with the same value are the same object exactly.

Now, take a look at this :

Equals With object

String a = "Java is great!";
String b = new String("Java is great!");
if(a == b)
    System.out.println("The strings are equale");
else
    System.out.println("The two strings are not the same Object");
if(a.equals(b))
   System.out.println("But they hold the same string");

The output of the above is:

The two strings are not the same Object
But they hold the same string

So you see why it is important to use equals for string comparison.

Let’s see the following snippet:

Equals With different Case

String a = "Java is great!";
String b = "Java Is Great!"; 
if (a.compareTo(b) == 0)
     System.out.println("Strings are equal");
 else
     System.out.println("Strings are NOT equal");

The above prints out :

Strings are NOT equal

This is because Strings in Java are case-sensitive, no matter the platform you are working on.

3. Using equalsIgnoreCase

If you don’t want to make case sensitive comparison, aka for you, the strings “abcd” and “AbCD” are the equal, then you can use equalsIgnoreCase:

equalsIngoreCase

String a = "Java is great!";
String b = "Java Is Great!"; 
if (a.compareTo(b) == 0)
     System.out.println("Strings are equal");
 else
     System.out.println("Strings are NOT equal");

This will print out:

Strings are equal

4. Using compareTo

This is useful to make lexicographical comparison between two strings. This generates the Unicode value of each character in the string and compares with the Unicode value of other string.

CompareTo

String a = "Java is great!";
String b = "Java Is Great!"; 
if (a.compareTo(b) == 0)
     System.out.println("Strings are equal");
 else
     System.out.println("Strings are NOT equal");
System.out.println("a>b:"+a.compareTo(b));

In the example above, it does character by character comparison. As soon as it reaches the character “I”, the comparison ends. The Unicode value for ‘i’ is 105 while ‘I’ is 73. So result is returned as 32 and no further comparison proceeds. Result of running this program is indicated below

Strings are NOT equal
a>b:32

5. Using contentEquals

To understand contentEquals, we have to understand CharSequence interface. This was introduced after the concrete implementation of String. This method allows a String to be compared with any other implementations of CharSequence such as StringBuilder and StringBuffer. It does a character by character comparison and if any of the characters do not match, it returns false.

CompareTo

String a = "Java is great!";
String b = "Java Is Great!"; 
if (a.contentEquals(new StringBuilder(b)))
      System.out.println("Strings are equal");
 else
      System.out.println("Strings are NOT equal");

This will print out:

Strings are NOT equal

6. Using comparison with literals

As we’ve said in the previous tutorial, literals are implemented as instances of String. We can compare literals like they were string objects.

Let’s see:

Literal Comparison-1

     String a = "abc";
     String b = "aBc";
     System.out.println(a.equals("abc"));
     System.out.println(b.equalsIgnoreCase("abc"));
     System.out.println(a.compareTo("abc"));
     System.out.println(b.contentEquals("abc"));

You can also do it like so:

Literal Comparison-2

     String a = "abc";
     String b = "aBc";
     System.out.println("abc".equals(a));
     System.out.println("abc".equalsIgnoreCase(b));
     System.out.println("abc".compareTo(a));
     System.out.println("abc".contentEquals(b));

This way you can avoid NullPointerException. But be careful because the absence of NullPointerException doesn’t make the program correct.

This was an example on how to compare Strings in Java.

7. Download the Source code

That was an example on Java Compare Strings.

Download
You can download the full source code of this example here: Java Compare Strings Example

Last updated on Sept. 23, 2019

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button