How to Compare two Strings in Java How to Compare two Strings in Java

Page content

In this tutorial, we’ll learn different ways to compare two strings in Java

Compare Strings using “==” operator

 1String string1 = "CodingNConcepts";
 2String string2 = "CodingNConcepts";
 3String string3 = new String("CodingNConcepts");
 4String string4 = new String("CodingNConcepts");
 5
 6System.out.println(string1 == string2);    // true
 7System.out.println(string1 == string3);    // false
 8System.out.println(string3 == string4);    // false
 9
10string3 = string3.intern();
11string4 = string4.intern();
12
13System.out.println(string1 == string3);    // true
14System.out.println(string3 == string4);    // true
Explanation
  • line 6: string1 and string2 both are initialized using literal so they both are referring to same string stored in String-Pool
  • line 7: string3 is initialized using New so it always creates a new string object in Java heap memory whereas string1 refers to string from String-Pool
  • line 8: Since String initialized using New always create a new string object, string3 and string4 both refers to different string object in heap memory
  • line 10,11: When you call intern() on a string, it returns a string from String-Pool if exist otherwise a new string is created in String-Pool and returned.
    So now after executing line 10 and 11, string3 and string4 refers to same string from String-Pool
  • line 13,14: After executing line 10 and 11, all four strings string1, string2, string3 and string4 refers to same string from String-Pool

Compare Strings using equals() method

String’s equals() method - returns true if the string argument is not null and both the comparing strings have the same sequence of characters in same case.

1String string1 = "CodingNConcepts";
2String string2 = "CodingNConcepts";
3String string3 = new String("CodingNConcepts");
4String string4 = new String("CODINGNCONCEPTS");
5
6System.out.println(string1.equals(string2));   // true
7System.out.println(string1.equals(string3));   // true
8System.out.println(string1.equals(string4));   // false
9System.out.println(string1.equals(null));      // false
Explanation
  • line 6: string1 and string2 both have same character sequence
  • line 7: string1 and string3 both have same character sequence
  • line 8: string1 and string4 both have same character sequence but case is different
  • line 9: string argument is null