What will happen if a string's value is set to an expression including an object?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



What will happen if a string's value is set to an expression including an object?



I wonder what functions will be called if a string's value contains an object?



For example:


public class A

A a;
String str = "Hello" + a;



Does it also call String.valueOf(Object) as System.out.println() does?


String.valueOf(Object)


System.out.println()





The object's "toString()" method is called.
– JohanLarsson
Aug 12 at 8:35





1 Answer
1



See jls 15.18.1. String Concatenation Operator +:



If only one operand expression is of type String, then string
conversion (§5.1.11) is performed on the other operand to produce a
string at run time.



and jls 5.1.11. String Conversion:



If the reference is null, it is converted to the string "null" (four
ASCII characters n, u, l, l).



Otherwise, the conversion is performed as if by an invocation of the
toString method of the referenced object with no arguments; but if the
result of invoking the toString method is null, then the string "null"
is used instead.



The toString method is defined by the primordial class Object
(§4.3.2). Many classes override it, notably Boolean, Character,
Integer, Long, Float, Double, and String.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard