Cilenco
Cilenco

Reputation: 7127

Java File constructor - Combine File object with String

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?

Upvotes: 0

Views: 83

Answers (1)

rgettman
rgettman

Reputation: 178283

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.

Upvotes: 7

Related Questions