Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return or Print StringBuilder? Java

Tags:

java

I am a bit confused about the StringBuilder. It seems that when I print a StringBuilder, there it no need to add .toString() because it will automatically give me a string representation. However, when I return a StringBuilder object, I have to add the .toString(). Is that true? and why?

Also, I am bit confused about the following code:

package com.tutorialspoint;
import java.lang.*;
public class StringBuilderDemo {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("India ");
        System.out.println("string = " + str);

        // append character to the StringBuilder
        str.append('!');
        // convert to string object and print it
        System.out.println("After append = " + str.toString());

        str = new StringBuilder("Hi "); 
        System.out.println("string = " + str);
        // append integer to the StringBuilder
        str.append(123);
        // convert to string object and print it
        System.out.println("After append = " + str.toString());
    }
}

For the different println, sometimes this code use toString and some other times it didn't. Why? I tried deleting the toString and the results are the same. Is it still necessary to use toString in println?

Thanks so much for helping a newbie out!

like image 694
whales Avatar asked Nov 30 '22 17:11

whales


2 Answers

When you print an object to a print stream, the String representation of that object will be printed, hence toString is invoked.

Some classes override Object#toString, amongst which StringBuilder does.

Hence explicitly invoking toString for StringBuilder is unnecessary.

On the other hand, other objects don't override toString. For instance, arrays.

When you print an array, unless using a utility such as Arrays.toString, you're getting the array's class type @ its hash code, as opposed to a human-readable representation of its contents.

like image 193
Mena Avatar answered Dec 09 '22 10:12

Mena


From the documentation:

Note that println() prints a string builder, as in:

System.out.println(sb);

because sb.toString() is called implicitly, as it is with any other object in a println() invocation.

like image 39
dguay Avatar answered Dec 09 '22 10:12

dguay