How to compare Stringbuffer objects?

Showing Answers 1 - 9 of 9 Answers

arun

  • Oct 3rd, 2005
 

pls refer to books for answer..

my question

can any one tell me what does that mean immutable - referring to strings

i am confused

String st="ss";

st="a"+st;

and other statement says

st=st+st.append("ss");

system.out.println(s);

  Was this answer useful?  Yes

Ravi Nagar

  • Oct 23rd, 2005
 

String objects are immutable. Well let me explain taking an example:Look at the code below along with the comments:String test = "Java"; // Create a string object "java" and assign a reference 'test ' to it.String test2 = test; //create another reference test2. Now both the references point to the //same string object i.e. "java"test = test + "world"; //this statement creates another string object i.e. "java world" and now the reference test refers to this object and not to "java" implying that string objects are immutable. The previous object "java" is then garbage collected if there is no other refrence to it. Right now test2 points to it, so it isnt garbage collected.System.out.println("test "+test);//Having understood the above, u can make out the output of this line. it will be "java world"System.out.println("test2 "+test2);//out put of this will be "java".Hope this makes it clear.

  Was this answer useful?  Yes

The Known fact is the stringbuffer strore the data as charcter array, so when when we do a append on the stringbuffer object it inserts the chars into that array.

Thats why we got method which can very the initial capacity of the same.

hope it clarifies the doubt?

  Was this answer useful?  Yes

Sarje

  • Aug 19th, 2009
 

Since java.lang.StringBuffer class does not override equals(Object obj) method of the Object class then so you can not compare its objects directly. If you want to compare its objects then first convert them into java.lang.String object and then compare. For example

class CompareDemo
{
    public static void main(String args[])
    {
        StringBuffer sb1 = new StringBuffer("Ram");
        StringBuffer sb2 = new StringBuffer("Ram");
        StringBuffer sb3 = new StringBuffer("Sita");
       
        String st1 = new String(sb1);
        String st2 = new String(sb2);
        String st3 = new String(sb3);
       
        System.out.println(st1.equals(st2));
        System.out.println(st1.equals(st3));
    }
}
output   true    false

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions