techbro
asked on
Using StringBuffer and StringBuidler
When I run this code below, the output that comes are
But I was expecting: blooperwhopper blooperwhoppershopper
I am confused why "whopper" is not included between blooper and shopper (second output).
Could you please provide me clear and detail explanation why "whopper" is not included in the second output?
blooperwhopper
bloopershopper
bloopershopper
But I was expecting: blooperwhopper blooperwhoppershopper
I am confused why "whopper" is not included between blooper and shopper (second output).
public class TestClass {
public static void main(String[] args) {
StringBuffer s = new StringBuffer("blooper");
StringBuilder sb = new StringBuilder(s);
s.append("whopper");
sb.append("shopper");
System.out.println(s);
System.out.println(sb);
}
}
Could you please provide me clear and detail explanation why "whopper" is not included in the second output?
'whopper' is appended *after* sb has been initialised with the value of s (ie. it taks a copy at line 5)
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
and when you then append "whooper" sb is another object altogether - it cannot hchange because
you cahnge the object which was used for its creatinion
you cahnge the object which was used for its creatinion
> and when you then append "whooper" sb is another object altogether - it cannot hchange because
> you cahnge the object which was used for its creatinion
thats incorrect. The object used for its creation is irrelevant. StringBuild copies the characters, it does not reference the String used to create it
> you cahnge the object which was used for its creatinion
thats incorrect. The object used for its creation is irrelevant. StringBuild copies the characters, it does not reference the String used to create it
So waht I wrote is correct, sb is another aobject altogether and it cannot change becauye abother
object whuch was used for its creation was now changed. It is relevent, vbecause that is exactly form where comes the confusion.
object whuch was used for its creation was now changed. It is relevent, vbecause that is exactly form where comes the confusion.
see my earlier comment, it explains what is going on
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you for your response.