- 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.1 2 3 4 5 6 7 8 9 10 | public class StringCompare{ public static void main(String args[]){ String str1 = "hello world"; String str2 = "hello world"; System.out.println( str1 == str2 ); # Return True System.out.println( str1.equals(str2) ); # Return 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;1 2 3 4 5 6 7 8 9 10 | public class StringCompare{ public static void main(String args[]){ String str1 = new String("hello world"); String str2 = new String("hello world"); System.out.println( str1 == str2 ); # Return False System.out.println( str1.equals(str2) ); # Return 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;1 2 3 4 5 6 7 8 9 10 | public class StringCompare{ public static void main(String args[]){ String str1 = "hello world"; String str2 = new String("hello world"); System.out.println( str1 == str2 ); # Return False System.out.println( str1.equals(str2) ); # Return 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.1 2 3 4 5 6 7 8 9 10 11 12 | import java.util.Objects; public class StringCompare{ public static void main(String args[]){ String str1 = null; String str2 = new String("hello world"); System.out.println(str1.equals(str2)); # Throw an Exception System.out.println(Objects.equals(str1, str2)); # Return False } } |
Comments
Post a Comment