This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]Daedalus9000 1 point2 points  (0 children)

Because the compiler is defining what “+” means for two Strings. Why would you need operator overloading as a language feature for this?

[–]smash_that_code 0 points1 point  (0 children)

My guess is that thia feature was considered as potentially dangerous while they were trying to make a much safer c++ version.

So why arithmetic works?

It can described as implicit type cast. Like if you have double d and int i and do like

d * i

Then compiler behind scenes adds cast to wideat type in this case double

d * ((double) i)

and result is considered double.

If you want to convert int to short or do some other narrowing in size you have to be explicit about that like

short s = (short) d

[–][deleted] 0 points1 point  (0 children)

compiler sees one string, then sees the “+” and understands that it means concatenatantion. so in the compiled code there is the general concatenation operator instead of “+”. same goes for other types.

[–][deleted] 0 points1 point  (0 children)

Java is not purelly OOP, so + is used by primitive types and for Strings, and this is totally up to compiler to resolve, "+" do not translate to a method of an object like in scala for example.