Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question:String and StringBuffer

 
Neha Sawant
Ranch Hand
Posts: 204
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
what is the output?
1)public class RefTest {
public static void main(String [] args) {
String a = "first";
StringBuffer b = new StringBuffer("second"); manipulate(a,b);
System.out.println("a = " + a + ", b = " + b );
}
static void manipulate(String x, StringBuffer y) { String temp = x;
x = y.toString();
y.append(":xtra");
y = new StringBuffer(temp);
}
}
2)public class TestBuffer {
public void myBuf(StringBuffer s, StringBuffer s1) {
s.append(" how are you");
s = s1;
}
public static void main(String args[]) {
TestBuffer tb = new TestBuffer();
StringBuffer s = new StringBuffer("Hello");
StringBuffer s1 = new StringBuffer("doing");
tb.myBuf(s, s1);
System.out.print(s);
}
}

 
Roopa Bagur
Ranch Hand
Posts: 267
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. a = first, b = second:xtra
2. Hello how are you (is the output)
Originally posted by Neha Sawant:
hi,
what is the output?
1)public class RefTest {
public static void main(String [] args) {
String a = "first";
StringBuffer b = new StringBuffer("second"); manipulate(a,b);
System.out.println("a = " + a + ", b = " + b );
}
static void manipulate(String x, StringBuffer y) { String temp = x;
x = y.toString();
y.append(":xtra");
y = new StringBuffer(temp);
}
}
2)public class TestBuffer {
public void myBuf(StringBuffer s, StringBuffer s1) {
s.append(" how are you");
s = s1;
}
public static void main(String args[]) {
TestBuffer tb = new TestBuffer();
StringBuffer s = new StringBuffer("Hello");
StringBuffer s1 = new StringBuffer("doing");
tb.myBuf(s, s1);
System.out.print(s);
}
}

 
Neha Sawant
Ranch Hand
Posts: 204
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi roopa,
thanx for prompt reply.

what significance does
y = new StringBuffer(temp); in question 1
and
s=s1 in question 2 have
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is to demonstrate that all arguments are passed by value. primitive value are copied and object references also !!! Since the reference is copied that means that you can't change the reference the caller provided as argument, but you can manipulate the referenced object though !
thus s=s1 won't change the reference s in the main method, the reference is only changed in the method manipulate but that's all.
HIH
------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic