Link to home
Start Free TrialLog in
Avatar of techbro
techbroFlag for United States of America

asked on

Using StringBuffer and StringBuidler

When I run this code below, the output that comes are

blooperwhopper
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);
  }
}

Open in new window


Could you please provide me clear and detail explanation why "whopper" is not included in the second output?
Avatar of Mick Barry
Mick Barry
Flag of Australia image

'whopper' is appended *after* sb has been initialised with the value of s (ie. it taks a copy at line 5)
SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
> 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
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.
see my earlier comment, it explains what is going on
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of techbro

ASKER

Thank you for your response.