Rock1431
Rock1431

Reputation: 131

Does toString create a new object when we call it on a String?

I was discussing String with my friend and came to know that calling toString() on a String creates new object? But even my friend doesn't know the reason. Can someone explain this to me?

Upvotes: 3

Views: 1056

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279900

The javadoc states

This object (which is already a string!) is itself returned.

so, no, it doesn't create a new object. Instead, a reference to the same object is returned. It could be (and is) implemented as

public String toString() {
    return this;
}

Note that String is immutable so it's a non-issue.

Upvotes: 8

Related Questions