Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Java: pass-by-value vs pass by reference  RSS feed

 
sai ohplease
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

_____________________________________

______________________________________
Can anyone explain me  why it prints "Webby" in the first example code instead of "Sparky". and also why it prints "Webby" in example 2?
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

It all has to do with Java® only supporting pass by value. There is no such thing as pass by reference in Java®, though C++ supports pass by reference.
In the first instance you pass a name to the method, and that name (or more precisely a reference to it) is copied into the parameter. If you change the value of the parameter inside the method, that doesn't affect the original. That is pass by value. The changes only affect the local copy, so Sparky never gets to the distant variable.
In the second case you only have one reference. You have one StringBuilder throughout and changes made inside the object in one place, e.g. changing its contents from "" to "Webby" are available anywhere else.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!