Results 1 to 4 of 4
Thread: Problem with code
- 08-04-2007, 05:29 PM #1
Member
- Join Date
- Jul 2007
- Posts
- 41
- Rep Power
- 0
Problem with code
I have this code:
The results are;Java Code:public class Test { public static void main (String[] args) { StringBuffer a = new StringBuffer("A"); StringBuffer b = new StringBuffer("[B]DD[/B]"); chng(a,b); System.out.println(a+","+b); } static void chng(StringBuffer x, StringBuffer y) { y.append(x); System.out.println("y 1: "+y); y = x; System.out.println("y 2: "+y); System.out.println("x 2: "+x); } }
y 1: BA
y 2: A
x 2: A
A,BA
I want to know why the last line of the result no equal to A,A?
- 08-04-2007, 06:35 PM #2
Member
- Join Date
- Aug 2007
- Posts
- 47
- Rep Power
- 0
Hi,
Because u made a side effect on the StringBuffer b by the append().
- 08-05-2007, 01:12 AM #3
StringBuffer y is a copy of the reference to StringBuffer b. As long as the reference y continues to refer/point to this same StringBuffer, modifications in y will affect b. When you point y to another StringBuffer then modifications to y will no longer affect b.
See How Arguments Are Passed to Java Methods for discussion.
- 08-05-2007, 05:57 PM #4
Member
- Join Date
- Jul 2007
- Posts
- 41
- Rep Power
- 0
Similar Threads
-
[SOLVED] Problem with code - inheritence
By yalla in forum New To JavaReplies: 1Last Post: 03-30-2008, 06:11 AM -
What is the answer yo my problem with this code
By masaka in forum New To JavaReplies: 4Last Post: 03-26-2008, 06:33 AM -
Problem with code
By jvasilj1 in forum New To JavaReplies: 5Last Post: 02-02-2008, 08:34 AM -
Problem with zero in my code
By fernando in forum New To JavaReplies: 1Last Post: 08-05-2007, 06:39 AM -
Problem with my first code
By paul in forum New To JavaReplies: 2Last Post: 07-26-2007, 04:09 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks