user6874839
user6874839

Reputation:

Returning stringbuilder object

What should be returned in this code? I am just working with StringBuilders and I don't know how I can return StringBuilder objects.

public String toProtocolString() {
    StringBuilder sb = new StringBuilder();
    sb.append(Integer.toString(points.length)).append(' ');
    sb.append(Integer.toString(points[0].length)).append(' ');
    for (int[] x : points)
        for (int y : x)
            sb.append(Integer.toString(y)).append(' ');
    //remove extra space at end
    sb.deleteCharAt(sb.length()-1);
    return ??????;

Upvotes: 1

Views: 1169

Answers (3)

U. Ahmad
U. Ahmad

Reputation: 76

To return a StringBuilder object you need to change the return type of your function signature from String to StringBuilder. But in most of the cases you don't want to do that because you will need another instance of StringBuilder in the callee method. So an elegant solution is that you return a variable of type String

In order to return a variable of type string just do this

return sb.toString();

Upvotes: 0

Naruto
Naruto

Reputation: 4329

Return string value of stringbuilder using toString() method. More about it is in doc

return sb.toString();

Upvotes: 0

Eran
Eran

Reputation: 393841

If you need to return a String, as the signature of your method suggests, you should

return sb.toString();

Otherwise, change the return type to StringBuilder and

return sb;

Upvotes: 1

Related Questions