Search code examples
javalanguage-historyunary-operator

What is the purpose of Java's unary plus operator?


Java's unary plus operator appears to have come over from C, via C++.

int result = +1;   

It appears to have the following effects:

  • Unboxes its operand, if it's a wrapper object
  • Promotes its operand to int, if it's not already an int or wider
  • Complicates slightly the parsing of evil expressions containing large numbers of consecutive plus signs

It seems to me that there are better/clearer ways to do all of these things.

In this SO question, concerning the counterpart operator in C#, someone said that "It's there to be overloaded if you feel the need."

However, in Java, one cannot overload any operator. So does this unary plus operator exist in Java only because it existed in C++?


Solution

  • The unary plus operator performs an automatic conversion to int when the type of its operand is byte, char, or short. This is called unary numeric promotion, and it enables you to do things like the following:

    char c = 'c';
    int i = +c;
    

    Granted, it's of limited use. But it does have a purpose. See the specification, specifically sections §15.15.3 and §5.6.1.