0

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

2 Answers 2

2

JVM calls the object's toString() method.

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

1 Comment

Thanks for editing. I wasn't sure if it was a runtime or compiler thing.
1
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 ...

Comments

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.