Learn Java – How To Compare Strings

The String class provides several methods for comparing strings. When a comparison is made between strings, the compiler compares the numbers of the objects, because each letter is represented by a number.

Comparisons with the equality operator (==) are used to compare values of primitive types; the result is true if both values are identical. If references are compared with the equal sign (==), the result is true if the two references indicate the same object in memory.

At other hand, .equals () is a method of the Object class, which compares the values of the literals stored by objects, so this method should be used to compare the literal values of type String variables.

Below some examples of comparisons looking for an exact match:


 

Other forms of comparison

Going a bit beyond the exact comparison of Strings, we have other interesting forms of comparison:

Case insensitive


 

A string that is contained in another


 

Which string is “bigger” than the other?


The compareTo method returns:

1 if the first String is bigger than the second

0 if they are equal

-1 if the first String is smaller than the second

Starts with


 

Ends with


 

If you want to explore more, visit our Java edu & tutorials section! Below are some examples:

You can also follow some of the broadcasters who program in Java, like the ones below:

How to compare strings in Java Java string programming java programming tips livecoding.tvcanal2048

How to compare strings in Java Java string programming java programming tips livecoding.tvBenjamin_Tennyson

Another cool way to find out interesting things about Java is to access our project page!

Read previous post:
learn-java-how-to-iterate-trough-a-hashmap-1
Learn Java – How To Iterate Through a HashMap

The use of HashMap is very common when working with values where it doesn't matter the position of the item...

Close