views:

369

answers:

5

Java's unary plus operator appears to have come over from C, via C++. As near as I can tell, it has 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 (or, at least, 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." But in Java, one cannot overload any operator. So does this operator exist in Java just because it existed in C++?

+3  A: 

I don't know, but I suspect it's there for symmetry with the (obviously necessary) unary minus operator.

Carl Manaster
It's entirely possible that if there weren't a unary plus operator in Java, I'd be sitting here on Stack Overflow complaining about it...
Syntactic
+2  A: 

My guess is it's there because sometimes typing the plus out makes things clearer. You might want to emphasize the fact that some number is positive, as opposed to some negative number.

Also, to provide a real world example where it's used, positive temperatures tend to be always prefixed with a plus in some parts of the world.

Matti Virkkunen
+2  A: 

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.

John Feminella
Right, but it's redundant in that case. Since that's a widening conversion, `int i = c;` will do the same thing.
Syntactic
It's not necessarily redundant in a holistic sense, because it conveys intention. One might legitimately wonder of `int i = c`, "did the author of this code mean to assign `c` to an `int`?" Are there other ways to do it? Sure, but this is the shortest way that also conveys intention.
John Feminella
Good point. I think in practice I'd be more likely to do `int i = (int) c;` if I wanted to convey intention, but using the `+` is certainly shorter.
Syntactic
A: 

One of Java's design goals was to be familiar (to a C/C++ developer), so when it came to operators like this I'm pretty sure they would have to have a strong reason to exclude it, not a good reason to need it.

Yishai
A: 

Many other languages have unary plus. It's customary to include it, and penny-pinching to exclude it.

EJP