Hi, i have written this program, 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)); StringBuffer ss2=sb1; System.out.println(ss2.equals(sb1)); System.out.println(sb2==ss2);
and got OUTPUT:: false false false dar true false
Actually i want to undersatnd this in terms of object refernce. What actually takes place in memory. So that i can understand String buffer much better as i am always confused with it.
read this: strings are immutable that once allocated memory cant b changed. where as strinbuffer variable is muttable, i.e. once allocated memory its contents can be changed.
if u get this concept,things are clearer then...
Teach me the art of forgetting, for I always remember wat I have forgotten.
Joined: Sep 12, 2005
Hi u have written......
will of course be false since the equals method in the Object class just checks if its the objects equals, not the content of the StringBuffer.
Then why this statement evaluates false
As both contain "Amit"
Joined: Sep 12, 2005
Also tell me if i want that comparision of sb1 and sb2 should return true value.......... let me make myself more clearer... I have created two instances of string Buffer and have stored same value in both say "Megha". as they are pointing to different memory locations, but i want to only compare the contains only and as both contain "megha" , it should return true value... But when i write .... SOP(sb1==sb2) it returns false....... how can i modify it so that i compare only the values and true value is returned
To clarify, the == operator results in true if and only if the two references point to the same object. By default, Object.equals() does the same thing. However, equals() can be overridden in any class to provide a more appropriate definition of equality. For example, String.equals() compares the contents of two String objects. However, StringBuffer does not override the equals() method, so it uses the default provide by Object.
I hope this helps you understand what is going on in your example.