How to Compare two Strings in Java

Java provides two options for string compare. First is == operator and second is .equals() function for Java string compare. This Java tutorial will help you to understand string comparison under Java and difference between == and .equals() for string comparison in Java.
  • Operator == checks for the object reference and matches true if both string belongs to same object.
  • Function .equals() checks for the value of string, it doesn’t matter to which object they belongs.

Compare Both Simple Strings:

If both string are simple strings. Java will consider them a same object. So both (== & equals()) will result as true.


Compare Both Strings are Objects:

If both string are an object strings. Java will consider them a different-2 objects. So == operator will return false and equals() function will result in true;


Compare One Simple Strings and One Object:

If on is simple string and other is an object strings. Java will consider them a different-2 objects. So == operator will return false and equals() function will result in true;


Compare with NULL String:

But in case of comparison with null string == will return false but .equals() function will throw an exception. To avoid null exception we can use Objects.equals(str1, str2) function like following example.


Thanks for Visit Here

Comments