soti84
soti84

Reputation: 93

Concatenating chars to a String - Using StringBuilder's append()

I was doing research on concatenating char primitive values to form a String and came across this post:

Concatenate chars to form String in java

I understand that the correct way of producing the final String value is to use the toString() method, how come that if I do not use this method, I still get the same output. I would have thought the following code would output the heap address of the object sb but it still prints 'ice'.

Thank you.

public class CharsToString {

    public static void main (String args[]) {

    char a, b, c;
    a = 'i';
    b = 'c';
    c = 'e';

    StringBuilder sb = new StringBuilder();
    sb.append(a);
    sb.append(b);
    sb.append(c);

    System.out.println(sb);
    }   
}

Upvotes: 1

Views: 760

Answers (5)

Michael Gantman
Michael Gantman

Reputation: 7808

System.out is a PrintStream class. So you look at javadoc for println(Object) for that class you will get your answer: https://docs.oracle.com/javase/8/docs/api/java/io/PrintStream.html#println-java.lang.Object-. In short if you invoke method println with parameter that is not primitive and not a String it will print output of toString() method of your object. So in your case calling System.out.println(sb.toString()); and System.out.println(sb); would have identical result

Upvotes: 0

MrSmith42
MrSmith42

Reputation: 10161

You need to look what System.out.println(sb); actually does. It calls in class java.io.PrintStream this method. (because a StringBuilder extends Object)

 public void println(Object x) {
        String s = String.valueOf(x);
        synchronized (this) {
            print(s);
            newLine();
        }
    }

And, String.valueOf(x) calls the toString() method on your StringBuilder.

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

Upvotes: 3

Hrabosch
Hrabosch

Reputation: 1583

This is because method toString() is called implicitly. Everytime, when you try to print object, it looks for toString() method. In this case, println method accept Object and call String.valueOf(Object o) which return String value of Object.

Upvotes: 0

SomeDude
SomeDude

Reputation: 14238

If you check System.out.println(Object obj); System.out is a PrintStream and println( Object obj ) on the PrintStream calls String.valueOf( Object ),

The String.valueOf( Object ) calls toString() on the Object, so indirectly System.out.println( StringBuilder sb ) calls StringBuilder's toString(),

Now if your Object is other than StringBuilder, which doesn't have toString(), it will print getClass().getName() + "@" + Integer.toHexString(hashCode());

Upvotes: 0

studersi
studersi

Reputation: 1495

The toString() method of the StringBuilder object is automatically called implicitly.

Upvotes: 1

Related Questions