A use for unary "+"

7 AM February 12, 2005

I had always thought the unary plus operator was useless, but no, you can use it to cause odd compile errors. Take this program for example:

  1 public class Hmmm {

  2     public static void main(String[] args) {

  3         byte b = 0;

  4         b = +b;

  5     }

  6 }

It has a "Type mismatch: cannot convert from int to byte" error on line 4. The unary plus causes the value of b to be promoted to an int before it is used, and of course, one can't assign an int to a byte without a cast.

And I thought Java was a nice, simple language.

By alang | # | Comments (2)
(Posted to javablogs and Java)


At 20:01, 12 Feb 2005 Cameron wrote:

Quite logical, if you think about it ;-)

At 11:12, 13 Feb 2005 Andy Todd wrote:

And would this be a problem in Python?


Add Comment

(Not displayed)

(Leave blank line between paragraphs. URLs converted to links. HTML stripped. Indented source code will be formatted with <pre> tags.)

© 2003-2006 Alan Green