Hi! I have the following code: class StrBuf{ public static void main(String args[]){ String s1 = "abcde"; StringBuffer s2 = new StringBuffer("abcde"); if(s1.equals(s2)) System.out.println("s1 equals s2!"); if(s2.equals(s1)) System.out.println("s2 equals s1"); } } This does not print out anything upon execution. I thought it would print out the "s1 equals s2"(from the 1st if stmt). Can anyone explain the output? Thanks Sharda
Marilyn de Queiroz
Sheriff
Joined: Jul 22, 2000
Posts: 9033
10
posted
0
StringBuffer, unlike String, does not override the Object version of the equals() method. Therefore, for StringBuffer, the statement s1.equals(s2); is equivalent to s1 == s2 ;
Since s1 and s2 are different objects are not at the same address, they are not equal and nothing prints.
JavaBeginnersFaq "Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Sayed Ibrahim Hashimi
Ranch Hand
Joined: May 17, 2001
Posts: 148
posted
0
If you want to see if the contents of a StringBuffer and a String are equal then you should use the String method 'contentEquals(StringBuffer sb)'. For more info look at the API docs.