0

E.g, we can:

Integer i = 2;
++i;
// now i = 3

We know that Integer is a raw wrapper type that's immutable like string, so ++i actually will construct a new Integer object, right? So ++i could be equal to i = Integer.valueOf(i.intValue() + 1)

Question:

If java doesn't support operator overloading of ++ like C++ language, then how "++i" is compiled and run? Is it just a form of syntax sugar?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Troskyvs
  • 7,537
  • 7
  • 47
  • 115
  • 1
    It is syntactic sugar. The `Integer` is being unboxed to a primitive `int`, and then the `++` is applied that that, with the result being stored again in an `Integer`. – Tim Biegeleisen Jun 24 '22 at 07:33
  • Elaborate on what you mean by "support operator overloading". Clearly Java "has operators", but can they be overloaded? – Willem Jun 24 '22 at 07:36
  • the compiler (OpenJDK 18) *translates* it to byte code representing `Integer.valueOf(i.intValue() + 1)`, exactly as you posted – user16320675 Jun 24 '22 at 08:03
  • 1
    Of course, Java *has* overloaded operators. Most notably, `+` works on integers, floating point values, and even strings. What Java doesn’t support, is adding custom overloads. Applying operators on wrapper types, is a distraction, as unwrapping and rewrapping isn’t overloading at all, however, as said at the beginning, overloaded operators exists. – Holger Jun 24 '22 at 09:56

0 Answers0