Say I have the following code
URI uri = URI.create("https://example.com");
String myString = uri + "/something"; // why is this allowed and compiler doesnt complain?
I would have thought compiler would complain about adding a string to URI type
JVM calls the object's toString() method.
String myString = uri + "/something";
// why is this allowed and compiler doesnt complain?
There are two meanings for + in Java: numeric addition and string concatenation; see Assignment, Arithmetic, and Unary Operators.
The string concatenation meaning is adopted if one or both of the operand expressions is a String. In that case, the other operand is converted to a string by calling toString() on it. Therefore ...
String myString = uri + "/something";
means the almost1 the same thing as:
String myString = uri.toString().concat("/something");
1 - There is some special case handling for null ...