• 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
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

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: 28331
97
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: 28331
97
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!
 
Mo-om! You're embarassing me! Can you just read a tiny ad like a normal person?
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic