Question

1.

public static StringBuffer setString2(StringBuffer s)
{
    s.append("::1st word");
    return s;
}

static StringBuffer sbGlobal = new StringBuffer("before");

public static void main(String[] args)
{   
    System.out.println(setString2(sbGlobal));
}

2.

public static void setString(StringBuffer s)
{
    s.append("::1st word");
}

static StringBuffer sbGlobal = new StringBuffer("before");

public static void main(String[] args)
{
    setString(sbGlobal);
    System.out.println(sbGlobal);
}

Can anyone explain to me, if there is any difference here? Also which method is better, if there is any difference, and why?

Was it helpful?

Solution

StringBuffer is a mutable class. The setString2() method takes a StringBuffer as argument, modifies it, and also returns it. The setString() method takes a StringBuffer as argument, modifies it, but doesn't return it.

Both programs do the same thing and produce the same result. The second solution is cleaner though: there is no reason to return something that is passed as argument. Indeed, the caller already has a reference to the object that it passes as argument, and returning this object is thus useless, and causes confusion: why does the method return a StringBuffer? Is this StringBuffer the same as the one passed as argument, or a new one? Is the StringBuffer passed as argument modified, or is the method returning a modified copy of it?

The second method doesn't have all these ambiguities.

Side note: You shouldn't use StringBuffer anymore. Prefer StringBuilder instead.

OTHER TIPS

 public static StringBuffer setString2(StringBuffer s)
    {
        s.append("::1st word");
        return s;
    }

That above method returning the StringBuffer object, which is modified by append method. So while you are doing

System.out.println(setString2(sbGlobal));

That returned StringBuffer object which is appended by some String and that is printing.

Where as in Second case there is no return type and its void.

public static void setString(StringBuffer s)
    {
        s.append("::1st word");
    }

So the statement

 System.out.println(setString2(sbGlobal)); //compile error because of void

When you call

 setString(sbGlobal);

It modifying the StringBuffer object and now you are printing the sbGlobal Object

System.out.println(sbGlobal);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top