Skip to main content

String Operations

String Comparisons [null, ==, .equals()]

Learn Java string comparison methods: equals() vs == operator, compareTo() for sorting, and Objects.equals() for null-safe comparisons. Master string equality checks, avoid NullPointerException, and handle null strings in Java programming.

String comparison is common in Java, especially when checking equality, sorting strings, or dealing with null values. Java provides various ways to compare strings, each suited for different use cases:

  1. equals() vs. == operator.
  2. compareTo method.
  3. Handling null strings with Object.equals().

equals() method

The equals() method in the String class compares the content of two strings. It checks if the sequence of characters in both strings is identical. This method is case-sensitive, meaning "Java" and "java" are considered different strings.

Syntax:

boolean result = string1.equals(string2);

Example:

String str1 = "Hello";
String str2 = "Hello";
String str3 = "World";

boolean isEqual = str1.equals(str2);  // true, same content
boolean notEqual = str1.equals(str3); // false, different content
  • equals() checks if the actual characters in both strings are the same.
  • It's commonly used when we care about the value of the strings, not their reference.

== operator

The == operator, on the other hand, checks whether two strings point to the same memory location (reference equality), not whether their content is the same. It compares if two string variables reference the same object.

Example:

String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");

boolean refEqual1 = (s1 == s2);  // true, both refer to the same object in the String Pool
boolean refEqual2 = (s1 == s3);  // false, s3 is a new object even though content is the same
  • s1 == s2: Since both s1 and s2 refer to the same object in the String Pool, the result is true.
  • s1 == s3: Here, s3 is created using the new keyword, which means it’s a different object in memory, even though the content is the same, so == returns false.

When to use equals() and == ?🤔

Use equals() to compare the content of strings and use == when you want to compare references (i.e., check if two variables point to the same object).

Using compareTo() method

The compareTo() method is used for lexicographical comparison of two strings. It compares the strings character by character based on their Unicode values and returns an integer value representing their relative order.

  • Returns 0 if the two strings are equal.
  • Returns a negative value -1, if the first string comes before the second string lexicographically.
  • Returns a positive value 1, if the first string comes after the second string lexicographically.

Syntax:

int result = string1.compareTo(string2);

Example:

String str1 = "apple";
String str2 = "banana";
String str3 = "apple";

int result1 = str1.compareTo(str2);  // -1, "apple" comes before "banana"
int result2 = str1.compareTo(str3);  // 0, both strings are equal
int result3 = str2.compareTo(str1);  // 1, "banana" comes after "apple"

In this example:

  • str1.compareTo(str2) returns a negative number because "apple" is lexicographically smaller than "banana".
  • str1.compareTo(str3) returns 0 because the two strings are equal.
  • str2.compareTo(str1) returns a positive number because "banana" comes after "apple" in lexicographical order.

Case Sensitivity

The compareTo() method is case-sensitive, meaning "Apple" and "apple" are treated as different strings due to the difference in case.

Example:

String str1 = "Apple";
String str2 = "apple";

int result = str1.compareTo(str2);  // Negative value, "Apple" comes before "apple"

In this case, the method returns a negative number because, in Unicode, the uppercase 'A' has a smaller value than the lowercase 'a'.

Using compareToIgnoreCase()

If you want to compare strings lexicographically without considering case, Java provides the compareToIgnoreCase() method, which works the same as compareTo() but ignores the case of the characters.

Example:

String str1 = "Apple";
String str2 = "apple";

int result = str1.compareToIgnoreCase(str2);  // 0, considered equal ignoring case

Handling null strings

One common challenge when comparing strings is handling null values. If you call the equals() method on a null string, it will throw a NullPointerException. To avoid this, Java provides a safe method in the Objects class called Objects.equals().

Syntax:

boolean result = Objects.equals(string1, string2);

The Objects.equals() method safely compares two strings (or any other objects) and returns true if they are both null or if they have the same content. It prevents NullPointerException by handling null values gracefully.

Example:

String str1 = null;
String str2 = "Hello";
String str3 = "Hello";

boolean safeComparison1 = Objects.equals(str1, str2);  // false, str1 is null
boolean safeComparison2 = Objects.equals(str2, str3);  // true, content is the same

In the above example:

  • Objects.equals(str1, str2) returns false because str1 is null, and str2 is not.
  • Objects.equals(str2, str3) returns true because the content of both strings is the same.

Using Objects.equals() is particularly useful when comparing strings where either or both may be null, eliminating the need for manual null checks.

Summary

  • equals(): Use this method to compare the content of two strings.
  • == Operator: Compares references, not content. Only use when checking if two strings are the exact same object in memory.
  • compareTo(): Used for lexicographical comparison of strings. It returns an integer that indicates the relative order of the strings.
  • Objects.equals(): Safely compares two strings while avoiding NullPointerException by handling null values.