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)
© 2003-2006 Alan Green