Difference between == operator and equals() method
- ==: This == operator meant for address comparison.
- .equals(): This .equals() method meant for contain comparison. Here java and JAVA is consider as different.
- .equalsIgnoreCase(): This .equalsIgnoreCase() method meant for contain comparison but this ignore the case. JAVA and java will consider same.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.*; public class Main { public static void main(String[] args) { String str1="JAVA"; String str2="java"; System.out.println(str1==str2); System.out.println(str1=="JAVA"); System.out.println(str1.equals(str2)); System.out.println(str1.equals("JAVA")); System.out.println(str1.equalsIgnoreCase(str2)); } } |
Output:
1 2 3 4 |
false true false true |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
//== is always meant for referance comp //object.equals() always meant for referance comp //String.equals() menat for content comp String s1 = "Mumbai"; String s2 = "Mumbai"; System.out.println(s1==s2); //true System.out.println(s1.equals(s2)); //true String s3 = new String("Pune"); String s4 = new String("Pune"); System.out.println(s3==s4); //false System.out.println(s3.equals(s4)); //true StringBuffer s5 =new StringBuffer("Nagpur"); StringBuffer s6 =new StringBuffer("Nagpur"); System.out.println(s5==s6); //false System.out.println(s5.equals(s6)); //false |