Core Java

Java String Equals Example

In this article, we will focus on understanding the Java String equals method and == operator and its comparison.

The examples in this article are created using eclipse photon IDE and Java 8.

1. String in Java

We will first see how String works to understand more about the equals() method. In Java, Strings are objects. Strings can be created in 2 ways. An instance of String can be created with the new keyword as follows:

String s1 = new String("foo");

Another concise way of doing this is,

String s2 = "foo";

As you will see shortly these 2 lines of code are not the same. String objects created with the new instance are always created as new objects in the heap whereas string literal (String s2 in our example) returns an existing object in the String pool (an area in Java Heap Memory where all String literals are stored) if it already exists.

2. Example of String equals() method

The Java equals method considers 2 Strings as equal only if they have the same case sensitive sequence of characters.

StringEqualsExample.java

package com.javacodegeeks.corejava;

public class StringEqualsExample {

	public static void main(String[] args) {
		
		String s1 = new String("foo");
		String s2 = new String("Foo");
		String s3 = "foo";
		
		//returns false
        System.out.println("s1.equals(s2) is "+s1.equals(s2));
         
        //s1.equals(s3) returns true
        System.out.println("s1.equals(s3) is "+ s1.equals(s3));  
	}

}

Output

s1.equals(s2) is false
s1.equals(s3) is true

The result of String equals() will be true only if the argument is not null and the character sequence exactly matches along with the case.

3. Example of == operator with String

The == operator checks the reference of the variables. In other words, checks if both objects point to the same memory location.

StringLiteralComparisonExample.java

package com.javacodegeeks.corejava;

public class StringLiteralComparisonExample {

	public static void main(String[] args) {
		
		String s4 = "foo";
		String s5 = "foo";
		String s6 = new String("foo");
		
		// s4 and s5 references the same object in the string pool
		System.out.println("s4 == s5 is "+ (s4 == s5)); 
		
		// although s4 and s6 has the same value "foo", they are two different objects
		System.out.println("s4 == s6 is "+ (s4 == s6));
		
	}

}

Output

s4 == s5 is true
s4 == s6 is false

Notice, s4 == s6 returns false although they have the same character sequence because they are references to different objects in the heap memory.

4. Comparison between String equals and == operator

In summary, the difference between the equals() method and == operator are:

  • The equals() method is used to check only the contents of the String in a case sensitive manner.
  • The == operator is primarily used for comparing primitive types. For Strings, it compares only the memory address and not its contents.
Fig. 1: String equals() and == comparison
Fig. 1: String equals() and == comparison

The above diagram pictorially represents the difference between equals() method and == operator.

5. The “.equalsIgnoreCase()” method

In Java, the equalsIgnoreCase() method is a string comparison method that checks if two strings are equal, ignoring their case differences. It is used to compare two strings without considering whether the letters are uppercase or lowercase. Here’s the syntax of the equalsIgnoreCase() method:
Syntax

public boolean equalsIgnoreCase(String anotherString)

The method takes in a single parameter, anotherString, which represents the string to be compared with the current string. It returns a boolean value: true if the two strings are equal (ignoring case), and false otherwise. Here’s an example that demonstrates the usage of equalsIgnoreCase():

Example

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

boolean isEqual1 = str1.equalsIgnoreCase(str2);
boolean isEqual2 = str1.equalsIgnoreCase(str3);

System.out.println(isEqual1);  // Output: true
System.out.println(isEqual2);  // Output: false

In this example, str1 is compared to str2 and str3 using the equalsIgnoreCase() method. Since str1 and str2 have the same characters, ignoring the case, the comparison returns true. However, str1 and str3 have different characters, so the comparison returns false.
The equalsIgnoreCase() method is particularly useful when you want to compare strings without being concerned about the case of the characters, such as when accepting user input or performing case-insensitive searches.

6. Performance Considerations

  • String Comparison Approaches:
    • equals() method: Compares two strings for exact character sequence equality, considering both the characters and their order.
    • equalsIgnoreCase() method: Compares two strings for equality while ignoring case differences.
    • == operator: Checks if two string references point to the same memory location rather than comparing the actual content of the strings.
  • Performance Implications:
    • Time Complexity: Both equals() and equalsIgnoreCase() methods have a time complexity of O(n), where n is the length of the strings being compared.
    • Space Complexity: The space complexity of string comparison operations is generally O(1).
    • Cultural Considerations: When using equalsIgnoreCase(), keep in mind that it performs case-insensitive comparisons based on the default locale.
  • Optimizing String Equality Comparisons:
    • Use == for String Interning.
    • Short-circuit Comparisons.
    • Cache String Comparisons.

By considering these performance considerations and optimizing string equality comparisons, you can enhance the performance of your Java applications, especially in situations where string comparisons are critical and frequent.

7. The “String.intern()” method

In Java, the intern() method is used to place a String object into the string pool, which is a pool of unique strings maintained by the JVM. When a string is interned, subsequent occurrences of the same string (with the same character sequence) will refer to the same memory location in the pool. This can help optimize memory usage and improve performance when working with a large number of strings. Here’s an example that demonstrates the usage of the intern() method:

Example

String str1 = "Hello";
String str2 = new String("Hello");
String str3 = str2.intern();

boolean isEqual1 = str1 == str2;
boolean isEqual2 = str1 == str3;

System.out.println(isEqual1);  // Output: false
System.out.println(isEqual2);  // Output: true

In this example, str1 is a string literal assigned to the variable str1. str2 is created using the new keyword, which allocates a new memory location for the string. Then, the intern() method is called on str2, which places it in the string pool.

When we compare str1 and str2 using the == operator, it returns false because they refer to different memory locations. However, when we compare str1 and str3, both of which reference the interned string “Hello”, the == operator returns true because they share the same memory location in the string pool.

By interning strings using the intern() method, you can reduce memory consumption and improve performance by reusing existing strings from the string pool instead of creating new instances for each occurrence of the same character sequence. However, it’s important to note that excessive use of string interning can also increase memory usage, so it should be used judiciously in situations where string comparisons and memory optimization are critical.

8. Download The Java String Equals Source Code

Download
You can download the full source code of this example here: Java String Equals Example

Vaishnavie Jayendran

I have done my Bachelor of Engineering in Computer Science. I have worked primarily in Java and related open source frameworks. Learning and exploring new technologies is my passion
Subscribe
Notify of
guest

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

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
dvalinoc
5 years ago

There is a mistake in your article, concerning the part 2 about equals method. The anwsers are opposite.
s1.equals(s2) is false, and s1.equals(s3) is true. To be sure, I tried that in junit

Back to top button