How does the String class override the + operator?

前端 未结 7 2012
刺人心
刺人心 2020-11-22 12:25

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

7条回答
  •  心在旅途
    2020-11-22 12:50

    It is Java compiler feature which checks the operands of + operator. And based on the operands it generates the byte code:

    • For String, it generates code to concat strings
    • For Numbers, it generates code to add numbers.

    This is what the Java spec says:

    The operators + and - are called the additive operators. AdditiveExpression: MultiplicativeExpression AdditiveExpression + MultiplicativeExpression AdditiveExpression - MultiplicativeExpression

    The 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 is String, 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.

提交回复
热议问题