Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Effect of invoking toString() method on String object

Tags:

java

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?

like image 961
Aditya Avatar asked Nov 22 '25 15:11

Aditya


2 Answers

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

public String toString() {
    return this;
}
like image 125
Andremoniy Avatar answered Nov 24 '25 05:11

Andremoniy


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?
like image 43
mtk Avatar answered Nov 24 '25 05:11

mtk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!