How does the String class override the + operator?

前端 未结 7 2013
刺人心
刺人心 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:44

    The meaning of the + operator when applied to String is defined by the language, as everyone has written already. Since you don't seem to find this sufficiently convincing, consider this:

    Ints, floats and doubles all have different binary representations, and therefore adding two ints is a different operation, in terms of bit manipulation, than adding two floats: For ints you can add bit by bit, carrying a bit and checking for overflow; for floats you must deal with the mantissas and exponents separately.

    So, in principle, "addition" depends on the nature of the objects being "added". Java defines it for Strings as well as ints and floats (longs, doubles, ...)

提交回复
热议问题