Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is toString() defined to return this for a java.lang.String?

Tags:

Consider

String foo = s.toString(); 

for a non-null java.lang.String instance s.

Is this defined to return itself, or is it up to a particular Java implementation? Out of interest is a "deep copy" taken?

Examining my source code of my JDK affirms that s is returned, but does the JLS insist on that? I've been brought up to regard toString() as an arbitrary serialisation, perhaps representative of the object, but not necessarily so. For example, it's entirely plausible (in my opinion at least) that an implementation could surround the string in quotation characters.

like image 419
P45 Imminent Avatar asked Apr 26 '17 08:04

P45 Imminent


People also ask

What does toString () do in Java?

The toString method is used to return a string representation of an object. If any object is printed, the toString() method is internally invoked by the java compiler. Else, the user implemented or overridden toString() method is called.

What is the return type of the toString () method in Java Lang object class?

toString() method returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read.

Is toString a return method?

A toString() is an in-built method in Java that returns the value given to it in string format. Hence, any object that this method is applied on, will then be returned as a string object.

In which of the following is toString () method defined * Java Lang object Java Lang string Java Lang Util none?

18. In which of the following is toString() method defined? toString() is defined in java. lang.


1 Answers

You wouldn't find any guarantee in the JLS but you do have one in the javadoc:

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

like image 108
assylias Avatar answered Oct 24 '22 08:10

assylias