"a == b" ##:
It compares references not values. Return type is boolean. == is used in rare situations where you know you’re dealing with interned strings.
**
"a.equals(b)"
It compares values lexicographically and returns an integer value that describes if first string is less than, equal to or greater than second string.For example,if str1 and str2 are two string variables then if
**
Example for String
// Java program to show how to compare Strings
public class Test
{
public static void main(String[] args)
{
String s1 = "Ram";
String s2 = "Ram";
String s3 = new String(" Ram");
String s4 = new String(" Ram");
String s5 = "Shyam";
String nulls1 = null;
String nulls2 = null;
System.out.println(" Comparing strings with equals:");
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s5));
System.out.println(" Comparing strings with ==:");
System.out.println(s1==s2);
System.out.println(s1==s3);
System.out.println(s3==s4);
System.out.println(" Comparing strings with compareto:");
System.out.println(s1.compareTo(s3));
System.out.println(s1.compareTo(s5));
}
}
Output:
Comparing strings with equals:
true
true
false
Comparing strings with ==:
true
false
false
Comparing strings with compareto:
0
-1