This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
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.
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.)
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Joined: Oct 13, 2005
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!
What does it mean when we say unary operator is used for promotion ?? How is it use for promotion ??
Have the determination of mirror which never fails to reflect in spite of being broken into pieces.<br /> <br />Kiss the hands you cannot bite.<br /> <br />An Optimist is one who starts taking a bath when he accidentally falls into the water.
Joined: Oct 13, 2005
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.