# 4 ways to compare strings in Java

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Aug 10, 2019, updated Feb 18, 2020. Topics: Java.
Canonical URL: https://attacomsian.com/blog/ways-to-compare-strings-in-java

> Learn about four different ways to compare two strings in Java.

Since `String` is a popular data type in Java, the string comparison is probably one of the most commonly used operations. Strings can be compared based on their content as well as their reference.

In this tutorial, we will learn about the following ways to compare two strings with each other:

* By comparison (`==`)  operator
* By  `equals()` method
* By `Objects.equals()` method
* By `compareTo()` method

## 1. Using Comparison (`==`) Operator

The comparison operator compares two strings by their reference. It does not take into account strings' values and the only **checks the referential equality of two strings**. It returns true if both strings refer to the same object, otherwise false.

```java
String str1 = "Spring Boot";
String str2 = "Spring Boot";
String str3 = new String("Spring Boot");

System.out.println(str1 == str2); // true
System.out.println(str2 == str3); // false
```

Look at the above examples. The comparison between 1st and 2nd string returns true because both these variables refer to the same string literal.

On the other hand, when we compare the 2nd string with 3rd string, it returns false. This is because both these strings are pointing to different objects (literal vs object).

Be careful while using comparison (`==`) operator for matching strings. It can potentially lead to unexpected results if you are not sure about the string types.

## 2. Using `equals()` method

The `equals()` method is part of `String` class inherited from `Object` class. This method **compares two strings based on their contents** &mdash; character by characters, ignoring their references.

It returns true if both strings have equal length and all characters are in the same order:

```java
String str1 = "Spring Boot";
String str2 = "Spring Boot";
String str3 = new String("Spring Boot");
String str4 = new String("SPRING BOOT");

System.out.println(str1.equals(str2)); // true
System.out.println(str2.equals(str3)); // true
System.out.println(str2.equals(str4)); // false
```

In the above examples, the first two comparisons are true because `str1`, `str2`, and `str3` all have the same contents irrespective of their references. Although `str4` has the same content in uppercase `equals()` returns false as it is case-sensitive. 

> Unlike `==` operator which handles null strings well, calling `equals()` method from a null string will cause a `NullPointerException` exception. However, if the string passed to `equals()` method is null, it returns false.

### `equalsIgnoreCase()` method

If you want to ignore the content case, use `equalsIgnoreCase()` method instead. This method is similar to `equals()` but **does not consider the casing in characters** while comparing strings:

```java
System.out.println(str2.equalsIgnoreCase(str4)); // true
```

## 3. Using `compareTo()` method

The `compareTo()` method is a part of `String` class and **compares the strings character by character lexicographically** and returns an integer value that indicates whether the first string is less than (< 0 value), equal to (0 value), or greater than (> 0 value) the second string:

```java
String str1 = "Spring Boot";
String str2 = "Spring Boot";
String str3 = new String("Spring Boot");
String str4 = new String("SPRING BOOT");
        
System.out.println(str1.compareTo(str2)); // 0 (true)
System.out.println(str2.compareTo(str3)); // 0 (true)
System.out.println(str1.compareTo(str4)); // 32 (false)
```

> If any of the two strings is null, the `compareTo()` method throws a `NullPointerException` exception.

### `compareToIgnoreCase()` method

The `compareToIgnoreCase()` method is similar to `compareTo()` method except that it ignores characters case:

```java
System.out.println(str1.compareToIgnoreCase(str4)); // 0 (true)
```

## 4. Using `Objects.equals()` method

The `Objects` class is a part of the Java utility package which contains a static `equals()` method that can be used to compare two strings.

This method returns true if both strings are equal to each other and false otherwise. Consequently, if both strings are null, true is returned and if exactly one string is null, false is returned. Otherwise, equality is determined by using the `equals()` method of the first string.

```java
String str1 = "Spring Boot";
String str2 = "Spring Boot";
String str3 = new String("Spring Boot");
        
System.out.println(Objects.equals(str1, str2)); // true
System.out.println(Objects.equals(str1, str3)); // true
System.out.println(Objects.equals(null, str3)); // false
System.out.println(Objects.equals(null, null)); // true
```

Since `Objects.equals()` internally calls `String` class's `equals()` method, it is case-sensitive.

## Bonus: Using Apache Commons

The `StringUtils` class from Apache Commons Lang library has some very good methods for performing string-related operations. The `equals()` method of `StringUtils` class is a **null-safe version of the `equals()` method** of `String` class, which also handles null values. 

The `StringUtils` class also includes `equalsIgnoreCase()`, `compare()`, and `compareIgnoreCase()` methods:

```java
// use `equals()` and `equalsIgnoreCase()` methods
System.out.println(StringUtils.equals("Spring Boot", "Spring Boot")); // true
System.out.println(StringUtils.equalsIgnoreCase("Spring Boot", "SPRING BOOT")); // true

// use `compare()` and `compareIgnoreCase()` methods
System.out.println(StringUtils.compare("Spring Boot", "Spring Boot")); // true
System.out.println(StringUtils.compareIgnoreCase("Spring Boot", "SPRING BOOT")); // true

// `null` values
System.out.println(StringUtils.equals(null, "SPRING BOOT")); // false
System.out.println(StringUtils.equals(null, null)); // true
```

Before you start using `StringUtils` utility class methods, make sure that you have added Apache Commons Lang dependency to your project's `pom.xml` file:

```xml
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>
```

If you are using Gradle build tool, add the following to your project's `build.gradle` file:

```groovy
implementation 'org.apache.commons:commons-lang3:3.9'
```

## Conclusion

That's folks for comparing strings in Java. We discussed 4 different ways to compare two strings with each other. You should always use `Objects.equals()` as it is null-safe and performs better.
