Aditya
Aditya

Reputation: 1043

Effect of invoking toString() method on String object

I have a String object in my code like

String tempString = "Some String";

now if I write something as

tempString.toString();

will this create another String object in String pool?

Upvotes: 3

Views: 330

Answers (2)

mtk
mtk

Reputation: 13709

As answered by Andremoniy from the code. Here is the part from the javadoc

toString

public String toString()

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

Specified by:
    toString in interface CharSequence
Overrides:
    toString in class Object

Returns:
    the string itself.

So no new object is created in this case. Regarding the use, it's just extra piece of code you are adding and nothing else.

Other interesting read in this respect

  1. Java: does String's toString() method have any practical purpose?
  2. How to use the toString method in Java?

Upvotes: 1

Andremoniy
Andremoniy

Reputation: 34900

No, because toString() method in class String looks like this one:

public String toString() {
    return this;
}

Upvotes: 7

Related Questions