• Post Reply Bookmark Topic Watch Topic
  • New Topic

Pass by value and Strings  RSS feed

 
Faisal syed
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Folks,
Below is the snippet of code


I thought the first print statement would print "newString" as String is an object, and when we pass objects between methods, changing state of the object in any method reflects across the methods. Please correct my understanding
 
Joel Christophel
Ranch Hand
Posts: 250
1
Chrome Eclipse IDE
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Faisal syed wrote:
I thought the first print statement would print "newString" as String is an object, and when we pass objects between methods, changing state of the object in any method reflects across the methods. Please correct my understanding


You never actually change the state of the object. (Strings are immutable, meaning that String objects cannot be changed). In line 8, you are creating a new String object and assigning it to the parameter variable. The parameter variable is a copy of the main variable. They initially point to the same object, and even when the parameter variable is made to point at a different object (as in line 8), the main variable still points to the original object.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that the "reverse(s)" also does not change the string s points to - it also creates a new String. Since you don't catch the reference to that String, it is lost.
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is reverse(s) actually meant to be modifyString(s)?
 
Faisal syed
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes Mike. Thanks for the clarification Joel, that helped
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!