It seems like I have missed a point in my lecture somewhere and I have difficulty to understand the following test I have done with the equal method. Let see my code: Line 1 StringBuffer sb1 = new StringBuffer("JAVA"); Line 2 StringBuffer sb2 = new StringBuffer("JAVA"); Line 3 System.out.println( sb1.equals(sb2)); //false
Line 4 String s1 = new String("JAVA"); Line 5 String s2 = new String("JAVA"); Line 6 System.out.println( s1.equals(s2)); //true What I was expecting the same result in line 3 and 6. Could you give me an advice of where I can go for fixing my inquiry. Thanks
StringBuffer class does not override the equals method of the object class,so when you say System.out.println( sb1.equals(sb2)); it prints out false since the equals method of the Object gets called. To quote from Java API: The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values x and y, this method returns true if and only if x and y refer to the same object (x==y has the value true). In case of String class it overrides the equals method of the Object class and this returns true if the String are equal otherwise false .So thats why s1.equals(s2)) prints true.
Joined: Apr 30, 2000
Thanks I get it. I've try this way to get it. System.out.println( sb1.toString().equals(sb2.toString()));
Again guys, out there taking care of those questions let me say that I appreciate a lot.