• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What does the unary + operator mean?

 
Campbell Ritchie
Sheriff
Pie
Posts: 50175
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was just looking at this topic about shift operators, and I had a look at the Java Tutorial here.

It says the unary + operator makes a number positive, but numbers are positive anyway.

Now, I always thought the unary + was a promotion operator, making numbers take a larger space in memory, rather like casting a short to an int. This is what it says in the Java™ Language Specification:
15.15.3 Unary Plus Operator +
The type of the operand expression of the unary + operator must be a type that is convertible (�5.1.8) to a primitive numeric type, or a compile-time error occurs. Unary numeric promotion (�) is performed on the operand. The type of the unary plus expression is the promoted type of the operand. The result of the unary plus expression is not a variable, but a value, even if the result of the operand expression is a variable.

At run time, the value of the unary plus expression is the promoted value of the operand.

I can't find any recent threads about this topic.

Which is right? I think it's the Java Language Specification.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My understanding is that the unary + doesn't really "do" anything, other than unbox and/or widen the operand to at least an int (as the JLS states).

I think the Java Tutorial is just saying that the unary + denotes a positive number, but it's not really needed because this is the default anyway. (Note that it will not turn a negative value positive.)
 
Campbell Ritchie
Sheriff
Pie
Posts: 50175
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you. I think that is the same as what I always thought. I have tried +number where number is (byte) -42 and, would you believe, I got it to print out -42!
 
Shivit Agarwal
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What does it mean when we say unary operator is used for promotion ?? How is it use for promotion ??
 
Campbell Ritchie
Sheriff
Pie
Posts: 50175
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It means you are using 32 bits memory for a char or a byte or a short or 64 bits of memory for an int. I think it's 32 and 64 at least.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Shivit Agarwal:
What does it mean when we say unary operator is used for promotion ?? How is it use for promotion ??

See JLS - 5.6.1 Unary Numeric Promotion.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic