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

Stringbuffer remains unchanged in a method

 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the code below, I dont see why the value of "foo" remains unchanged in the method - changeFoo().
Output of this program is : I am foo

public class q1{
public static void changeFoo(StringBuffer foo) {
foo = new StringBuffer("I am not foo");
}

public static void main(String args[])
{
StringBuffer foo = new StringBuffer("I am foo");
changeFoo(foo);
System.out.println(foo.toString());
}
}
 
Bartender
Posts: 6663
5
MyEclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because the original reference retains its link to the object regardless of what some other method does with that reference.

You will notice however that if the reference points to a mutable object, any change in the object's contents will be visible to anyone that can access the reference. (Withholding memory barriers in multiple threads which is a topic whose discussion is out of scope)
 
Ranch Hand
Posts: 808
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
 
Ranch Hand
Posts: 100
Hibernate Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

May be you will read and understand it better if the variable name is changed a bit in changeFoo .



and look at dennis's comments in code.
 
grapes are vegan food pellets. Eat this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic