• 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 ...
  • Campbell Ritchie
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

Problem with StringBuffer and call by reference

Ranch Hand
Posts: 145
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
please c the code below.I thought answer should be "one more" will be printed twice,but output is
one more
public class Test {
public static void main(String args[]) {
StringBuffer a = new StringBuffer("One");
StringBuffer b = new StringBuffer("Two");
System.out.println("a is "+ a +"\nb is " + b);
static void swap (StringBuffer a, StringBuffer b) {
a.append(" more");
b=a;//what is happening over here
Author & Gold Digger
Posts: 7617
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In Java, everything is passed by value. A copy of a reference is passed to a method, so that you may interact and mutate the referenced object but not make the reference point to some other object.
So the statement b=a; in method swap has only a local effect, that is, b will point to a only in the method scope and the assignment does not affect the original StringBuffer outside of swap.
Read this: http://www.javaranch.com/campfire/StoryPassBy.jsp
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
    Bookmark Topic Watch Topic
  • New Topic