What is the output of the following? StringBuffer sb1 = new StringBuffer("Amit"); StringBuffer sb2 = new StringBuffer("Amit"); String ss1 = "Amit"; System.out.println(sb1 == sb2); System.out.println(sb1 .equals(sb2)); System.out.println(sb1 .equals(ss1)); System.out.println("Poddar".subString(3)); a) false false false dar b) false true false Poddar c) compiler error d) true true false dar The given answer is a. Doesn't StringBuffer don't have "==" or "equals()".....? Thanks
== operator compares the references In the given program, sb1 and sb2 are referring to different objects. So, sb1 == sb2 is false. String and StrinBuffer both have equals() method that compare two encapsulated strings. The StringBuffer class inherits its equals() method from Object, so the method does not perform expected behavior, which would be chracter by character comparison. And you cannot compare String to StrinBuffer.
-> sb1 == sb2 is false Since the object references will be will be compared -> sb1.equals(sb2) is false since StringBuffer does not have an equals method so the Object's equals method will be called (which does a comparision of the references) -> sb1.equals(ss1) is false. for the same reason as sb1.equals(sb2) -> "Poddar".subString(3) will give you "dar" provided you spell subString(3) with a lowercase 's' as substring(3).