• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Question from Sarga! String Buffer argument!

 
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,

public class TestBuffer
{
public static void main(String args[]) {
StringBuffer a = new StringBuffer("One");
StringBuffer b = new StringBuffer("Two");
TestBuffer t = new TestBuffer();
t.swap(a,b);
System.out.println("a is "+ a +"\nb is " + b);
}
static void swap (StringBuffer a, StringBuffer b) {
a.append(" more");
b=a;
}
}

Answer is
---------
What will be the output?
Answer:
a. a is One
b is Two
b. a is One
b is One
c. a is One more
b is One more
d. a is One more
b is Two
e. a is One more
b is Two more
The given answer is 'd' and my answer is 'c'. When I executed the program it gives 'd'.
I modified program like as follows to know the intermediate result:
static void swap (StringBuffer a, StringBuffer b) {
a.append(" more");
System.out.println("Before assign a is "+ a +"\nb is " + b);
b=a;
System.out.println("After Assign a is "+ a +"\nb is " + b);

Before assignment ,I am getting ' Before assign a is one more ' and 'b is two'.
After assignment,I am getting ' Before assign a is one more ' and 'b is one more'.
Then how come,when it goes to main it prints
a is one more and
b is two.
Please help me.
I could not run the 'sample test',it says 'File not found' 3 times and file creation error 2 times and bad command or file name.
I created director Jargon and uninstall 'install.zip'. Now this directory has 'jargon.zip','sarg.dat' and 'run.bat'. I checked resolution and it is fine. And try running like follows from c:\jdk1.2.1\bin\ java -jar c:\Jargon\jargon.zip. Same error I am getting.
Please help me and bear this big mail.
Thanks in advance
Nirmala
 
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Nirmala,
According to me, the reference values are copied over in the method, so, when the assignment b=a is performed in the method swap, only the copied reference is being changed, while the original reference which points to "Two" remains intact.
I hope I have made myself clear. I'm not too good at explaining things
Thanks,
Aman
 
reply
    Bookmark Topic Watch Topic
  • New Topic