Forums Register Login

question:String and StringBuffer

+Pie Number of slices to send: Send
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);
}
}

+Pie Number of slices to send: Send
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);
}
}


+Pie Number of slices to send: Send
hi roopa,
thanx for prompt reply.

what significance does
y = new StringBuffer(temp); in question 1
and
s=s1 in question 2 have
+Pie Number of slices to send: Send
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
Everybody's invited. Even this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 725 times.
Similar Threads
A String Buffer question,help!
don't understand
Queries
Question from Javacaps mock
I thought it should be "Hello" instead of "Hello how are you"
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 01:41:13.