Hi can someone let me know how == and equals work in the following cases ? String a1= new String("a") String a2= new String("a") Stirng a3=String("a") String a4=String("a") Stirng a5="a" String a6="a" a1==a2 a1.equals(a2) a3=a4 a3equals(a4) a5==a6 a5.equals(a6) a1==a3 a1.equals(a3) a1=a5 a1equals(a5) Will the ans remain same if all the above were StringBufferclasses instead of string objects ?
The == operator compares two variables to determine if they contain the same value. In the case of reference variables, that means that the == operator will determine if each variable contains the same value. That will only return true when both variables contain a reference to the same object. However, if a class, such as String, overrides the equals method, you can call that method to determine if two objects contain the same values, not to reference variables. Check out the JLS for more information: §15.21.3 Reference Equality Operators == and != Corey
There is a trick though with Strings. When a String is allocated with a new: String s = new String("ABC"); then all the regular rules apply because the String is allocated on the heap. So you will get this behavior: String a = new String("ABC"); String b = new String("ABC"); System.out.println(a == b) // prints false However if you declare a String using = instead of new: String c = "ABC"; the behavior is different because this String is allocated in the literal pool. So you get this behavior: String c = "ABC"; String d = "ABC"; System.out.println(c == d) // prints true of course, using .equals() method will find a, b, c, and d all equal.