String

Java Compare Strings Example

Photo of Nikos MaravitsasNikos MaravitsasMarch 6th, 2014Last Updated: June 16th, 2020
0 213 4 minutes read

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

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

The similarities stop here. AString 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 typeif(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 sameObject instance. Consequently,a andb 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 theequals method.

2. Java Compare Strings – Using equals

equals is a member of theObject 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 aboutin 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 ObjectBut they hold the same string

So you see why it is important to useequals forstring 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 becauseStrings 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 useequalsIgnoreCase:

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 equala>b:32

5. Using contentEquals

To understandcontentEquals, we have to understandCharSequence interface. This was introduced after the concrete implementation ofString. This method allows aString to be compared with any other implementations ofCharSequence such asStringBuilder andStringBuffer. 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 ofString. 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 avoidNullPointerException. But be careful because the absence ofNullPointerException 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

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Nikos MaravitsasNikos MaravitsasMarch 6th, 2014Last Updated: June 16th, 2020
0 213 4 minutes read
Photo of Nikos Maravitsas

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
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.