• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Changing the Parameter Variable + Appending in String

 
Greenhorn
Posts: 15
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Output: mother
For the above code, why does changing sb1, the parameter variable, change sb2?



Output: hey oh hi yo ey
For the above code, why is "hey oh hi" appended before "yo?"
 
Sheriff
Posts: 28370
99
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Dylan Kwon wrote:For the above code, why does changing sb1, the parameter variable, change sb2?



The code doesn't change the variable. It changes the StringBuilder which the variable refers to, which is also the StringBuilder which sb2 refers to. To change the variable would require code like "sb1 = ...".

For the above code, why is "hey oh hi" appended before "yo?"



It isn't exactly "appended" -- that isn't the word I would use. It's just written to the console before "yo" is written to the console. Look at the two System.out.println() statements and see what they print.
 
Paul Clapham
Sheriff
Posts: 28370
99
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It's also important to know that StringBuilder's "append" method actually changes the contents of the StringBuilder object. Whereas the "append" method of String does NOT change the contents of the String object. If the question had used String instead of StringBuilder, the result would have been different.
 
Dylan Kwon
Greenhorn
Posts: 15
1
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you so much, Paul this cleared up every question I had and more!
 
and POOF! You're gone! But look, this tiny ad is still here:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic