• 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
  • Paul Clapham
  • Ron McLeod
  • paul wheaton
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Liutauras Vilda
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Piet Souris
Bartenders:
  • salvin francis
  • Mikalai Zaikin
  • Himai Minh

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.
 
We begin by testing your absorbancy by exposing you to this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic