StringBuffer no-arg constructor
How do I assign a value to a stringBuffer object if I am using default constructor?
The following code does not compile:
Code:
public class StringBufferDemo {
public static void main(String args[])
{
StringBuffer sb1=new StringBuffer();
sb1="1234567890";
}
}
PS: I know we can use the constructor StringBuffer(String str), but what is the use of the no-arg constructor if we can assign values only by using StringBuffer(str)?
Re: StringBuffer no-arg constructor
I have never needed to do this so I don't know. But I just looked at the API and what I do know is how I could approach it and even test it. Did you read the API and look at the methods? Do you see anything that might provide an answer? If I have to read the API to help answer some of these questions then I expect you and others to make an attempt also.
Regards,
Jim
Re: StringBuffer no-arg constructor
a StringBuffer is not a String, so why are you trying to assign a String to a StringBuffer?
Re: StringBuffer no-arg constructor
There are four constructors for StringBuffer:
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
StringBuffer(CharSequence chars)
If I want to use the first version of the overloaded constructor, how to assign a value? You will be ultimately be using 3rd or 4th version of the constructor to assign the value, so what is the use of no-arg constructor?
Re: StringBuffer no-arg constructor
Suhaas, you need to get your terminology straight before continuing to post 'questions' here. The line Code:
StringBuffer sb = new StringBuffer();
declares a variable sb of type StringBuffer and assigns a value to it, a reference to a newly created StringBuffer.
What you are referring to as 'a value' is anybody's guess.
db
Re: StringBuffer no-arg constructor
Ok, lets use the line:
StringBuffer sb = new StringBuffer();
Now suppose I want to assign "abc" to it. How do I go about it?
Re: StringBuffer no-arg constructor
You're still not reading the API documentation. Do you want to be stuck forever? When are you actually going to LISTEN to the advice you ask for?
Re: StringBuffer no-arg constructor
Quote:
Originally Posted by
suhaas.mohandos@gmail.com
Ok, lets use the line:
StringBuffer sb = new StringBuffer();
Now suppose I want to assign "abc" to it. How do I go about it?
There isn't any way you can assign a String literal to a StringBuffer variable in Java.
Maybe you'd be happier with a language that isn't type safe.
db