Results 1 to 4 of 4
  1. #1
    oregon is offline Member
    Join Date
    Jul 2007
    Posts
    41
    Rep Power
    0

    Default Problem with code

    I have this code:
    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);
     }
     }
    The results are;

    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?

  2. #2
    henry_78 is offline Member
    Join Date
    Aug 2007
    Posts
    47
    Rep Power
    0

    Default

    Hi,
    Because u made a side effect on the StringBuffer b by the append().

  3. #3
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    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.

  4. #4
    oregon is offline Member
    Join Date
    Jul 2007
    Posts
    41
    Rep Power
    0

Similar Threads

  1. [SOLVED] Problem with code - inheritence
    By yalla in forum New To Java
    Replies: 1
    Last Post: 03-30-2008, 07:11 AM
  2. What is the answer yo my problem with this code
    By masaka in forum New To Java
    Replies: 4
    Last Post: 03-26-2008, 07:33 AM
  3. Problem with code
    By jvasilj1 in forum New To Java
    Replies: 5
    Last Post: 02-02-2008, 09:34 AM
  4. Problem with zero in my code
    By fernando in forum New To Java
    Replies: 1
    Last Post: 08-05-2007, 07:39 AM
  5. Problem with my first code
    By paul in forum New To Java
    Replies: 2
    Last Post: 07-26-2007, 05:09 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •