Search code examples
javaglobal-variablesmutable

Is there any difference between these two Java codes Snaps?


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?


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.