0

By a random I found out that the following code is valid in Java. Eclipse does not show an error and it does not come to a RuntimeException while using the programm:

File f1 = new File("");
File f2 = new File(f1 + "");

Why does that work? f1 is definitely not a String so why can we combine two different objects with the + operator? File is a direct subclass from Object and we can not merge a String with a File object because that are mainly different objects. File has also an uri constructor but why should this be an uri? File and uri are in technical view from java absolute different objects (again both are direct subclasses from object and have no context to each other) so why does this work?

1 Answer 1

7

This is possible because of String conversion. If the operator is +, one of the operands is a String, and the other is not, then String conversion takes place on the operand that isn't a String. It's converted to a String by having toString() called on it.

The JLS, Section 5.1.11, covers this:

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

...

Now only reference values need to be considered:

  • 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.

Sign up to request clarification or add additional context in comments.

1 Comment

To be precise, the effect is better described as invoking String.valueOf(...), passing the object reference as an argument: it also works for null references.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.