Thursday, 21 April 2016

java equals and == confusion











1. I know that == checks if two object are pointing to same memory location also the default definition of equals uses == to do the checking, means both are same.



2. String class overrides equals method to check if two string have same value.



Consider S1 = "test" and S2 = S1;




Now S1 and S2 are two different objects so as per point 1 S1==S2 should be false and as per point 2 S1.equals(S2) should be true but when I ran this small program in eclipse both return true. Is there any special thing about string objects that S1 == S2 is also true.


Answer




Consider S1 = "test" and S2 = S1; Now S1 and S2 are two different objects




Nope. This is where your argument fails.



You created one string object, and both your variables refer to the same string object. Assignment does not make a new copy of the string.



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...