Why does + work with Strings in Java?

前端 未结 6 1555
一向
一向 2020-12-19 06:26

Java can\'t do operator overloading, but + works okay for String and Integer and some other classes. How is this possible?

6条回答
  •  失恋的感觉
    2020-12-19 06:57

    It works for primitive wrappers like Integer because of autoboxing.

    It works for String because that's a special case for concatenating strings:

    The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java. For additional information on string concatenation and conversion, see Gosling, Joy, and Steele, The Java Language Specification.

提交回复
热议问题