• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

StringBuffer

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi can anyone explain this?
For the code given below answer is D.
I am confused!
contents of stringBuffer are mutable.In that case
in line 10 b is assigned the value of a so it should be one more,how come it is two?
Thanks.
public class Test {//line1
public static void main(String args[]) {//line2
StringBuffer a = new StringBuffer("One");//line3
StringBuffer b = new StringBuffer("Two");//line4
Test.swap(a,b);//line5
System.out.println("a is "+ a +"\nb is " + b);//line5
}//line7
static void swap (StringBuffer a, StringBuffer b) {//line8
a.append(" more");//line9
b=a;//line10
}
}
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
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Replace the swap method by this:

Then recall how java passes arguments to methods.
Is now it clearer why answer d) is correct?
 
praveena kuppachi
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes,I got it!
Thanks.
 
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Test {//line1
public static void main(String args[]) {//line2
String a = new String("One");//line3
String b = new String("Two");//line4
Test.swap(a,b);//line5
System.out.println("a is "+ a +"\nb is " + b);//line5
}//line7
static void swap (String a, String b) {//line8
a.concat(" more");//line9
b=a;//line10
}
}
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

try this you will find the significance of "StringBuffer is mutable!String is immutable!in fact,all contents of wrapper classes are immutable!" am I right?
[ February 12, 2003: Message edited by: Mellihoney Michael ]
 
If you try to please everybody, your progress is limited by the noisiest fool. And this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic