0

I'm working on an assignment right now, and am confused by this. The code given is simple:

public class Variables{
    public static void main(String[ ] args){
        StringBuffer b = "ghi";
        f(b);
        System.out.println(b):
    }

    public static void f(StringBuffer p){
        p.concat("jkl");
    }
}

The question simply asks what the output of the print statement will be. My first thought was simply "ghi", but this was incorrect. If the method f is taking b as a parameter and setting it to p, then how does .concat() modify b? I've read through the StringBuffer documentation and dont understand why this wouldn't end up with b equaling "ghi" while p is "ghijkl".

Basically, how is the .concat() method called on p also modifying b?

1
  • 2
    I doesn't modify b, it modifies the object referenced by b. b is not a StringBuffer, it's a reference (pointer) to a StringBuffer. (Understanding the difference between a reference and the thing referenced is critical to understanding most languages more sophisticated than BASIC.) Commented Oct 15, 2014 at 1:28

2 Answers 2

2

First, you need to create a StringBuffer correctly.

StringBuffer foo = new StringBuffer("some string");

You passed an object to a function. Java passes objects as references (the references themselves of course are passed by value). See: Is Java "pass-by-reference" or "pass-by-value"?

Since you have a reference to a StringBuffer and not a copy of it, you are actually modifying the same object as you would as if you were in main.

Sign up to request clarification or add additional context in comments.

2 Comments

I can't test it now, but I'm not sure you can assign a StringBuffer in that way. Don't you have to do StringBuffer foo = new StringBuffer("some string here")?
you are right it is the wrong way. please add to your answer so I can vote u up
1

This is the difference between parsing by reference and parsing by value.

When you create a method taking a primitive, for example, it undergoes what is called parsing by value. The JVM pretty much creates a copy of the value and that is what you get in the method.

int j = 0;
foo(k);
System.out.println(j); //Will still be 0.

public static void foo(int i) {
 //i is not j (what you called the method with), it is a copy of it that is only valid within this method
 i++;
}

Now when you call the method with an object such as a StringBuffer you are parsing by reference. This means that you are not parsing the value of the StringBuffer(not parsing a StringBuffer` with "ghi" as its contents), but you are rather parsing a pointer to it. Using this pointer you can still operate on the original object within other methods and bodies of code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.