简体   繁体   中英

Return or Print StringBuilder? 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!

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.

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.

If you try to append an object to a string like this : "string = " + str , the toString() method is implicitly called.

So no, it does not matter, if you specify it.

Also the toString() method itself (even when you are not append it to string) calls the toString() method.

Therefore System.out.println(str) and System.out.println(str.toString()) gives same result.

You don't need to use toString when you're printing it for one of two reasons. First, if you just print it out by itself, it's because there is a method println(Object) on the PrintStream class, which will call toString for you. That happens in this type of situation:

System.out.println(myStringBuilder); //Calling println(object)

The second possible reason is if you concatenate it with a String . In that situation, the compiler will do the calling of toString for you. In both cases, toString is still being called, it's just being done behind the scenes. That would be this situation:

System.out.println("String " + myStringBuilder); //println(String), plus compiler magic

When you return it from a method, the return type is defined as String . Since a StringBuilder is not a String , and there doesn't exist any sort of compiler magic to implicitly turn it into one, you need to do the conversion yourself.

String methodReturningString(){
    StringBuilder sb = new StringBuilder();
    //return sb; <- doesn't work, since a StringBuilder is not a String
    return sb.toString(); //Explicitly making the conversion yourself.
}

The first thing you should know about Java is that we work with objects and that all objects inherit methods from the class Object: http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html

This class has a toString() method and since every object inherits this method it can always be called on every object. When you do not override it, it usually returns the physical address of the object.

Like stated in other answers, whenever a string is expected in println for instance and you pass an object it automatically calls the method which requires an Object (note the capital, we are talking about the class Object here), it will then use the toString method on the object passed along as parameter. The reason you get the string you want is because StringBuilder overrides the toString() method for you.

When you in your own code want to pass the string in your StringBuilder you have two options. You can either pass StringBuilder.toString() or change the return type to Object or StringBuilder and call toString() when you actually need it.

Hope this clarifies why you can just pass the object instead of the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM