hi all the only difference between the string and stringbuffer is former is immutable the latter is muttable.
but i baffled at the output of the following code
1. 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));
Ans: a) false false false dar b) false true false Poddar c) Compiler Error d) true true false dar
Actually the StringBuffer class doesn't override the equals() method.so when you call the equals method by sb1.equals(sb2),it will call the parent class equals() method ie,Object class.
The basic rule is when you override the equals() method you should override the hashCode() method also.so, when you call the equals() method of Object class it will call the hashCode()method of Object class.if you check the eqauls() and hashCode() methods explanation in API Reference,they clearly mentioned that
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)
so it will return different hashCode values.so you will get false.