How can java class instance be added with string?

koo :
public class ProductTest{
    public static void main(String[] args){
        Product pr=new Product();
        System.out.println(pr); /// Product@hashcode
    }
}

class Product{
}

I can understand the above output of Product@hashcode since println method internally uses valueOf method and converts it into the string.

But I cannot explain the behavior of output below,

public class ProductTest{
    public static void main(String[] args){
        Product pr=new Product();
        String str=pr + "something";
        System.out.println(str); // Product@hashcodesomething
    }
}

class Product{
}

How can class instance and string literal be added together?

What am I missing?

Sweeper :

This is specified in the Java Language Specification §15.18.1:

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.

A string conversion is further specified like this:

Any type may be converted to type String by string conversion.

[...]

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.

So something like pr + "something" is equivalent to String.valueOf(pr) + "something".

Note that I used valueOf instead of toString, because pr.toString() would throw an exception in case pr is null. String.valueOf() would not.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=139425&siteId=1