Why in Java you\'re able to add Strings with the + operator, when String is a class? In theString.java
code I did not find any implementation for this operator
It is Java compiler feature which checks the operands of +
operator. And based on the operands it generates the byte code:
This is what the Java spec says:
The operators + and
-
are called the additive operators. AdditiveExpression: MultiplicativeExpression AdditiveExpression + MultiplicativeExpression AdditiveExpression - MultiplicativeExpressionThe additive operators have the same precedence and are syntactically left associative (they group left-to-right). If the type of either operand of a
+
operator isString
, then the operation is string concatenation.Otherwise, the type of each of the operands of the
+
operator must be a type that is convertible (§5.1.8)to a primitive numeric type, or a compile-time error occurs.In every case, the type of each of the operands of the binary
-
operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.