Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of Java's unary plus operator?

Java's unary plus operator appears to have come over from C, via C++.

int result = +1;    

It appears to have 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/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."

However, in Java, one cannot overload any operator. So does this unary plus operator exist in Java only because it existed in C++?

like image 439
Syntactic Avatar asked Apr 12 '10 18:04

Syntactic


2 Answers

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.

like image 82
John Feminella Avatar answered Sep 26 '22 03:09

John Feminella


Here's a short demonstration of what the unary plus will do to a Character variable:

private static void method(int i){     System.out.println("int: " + i); }  private static void method(char c){     System.out.println("char: " + c); }  public static void main(String[] args) {     Character ch = 'X';     method(ch);     method(+ch);         } 

The output of running this programme is:

char: X int: 88 

How it works: Unary + or - unbox their operand, if it's a wrapper object, then promote their operand to int, if not already an int or wider. So, as we can see, while the first call to method will choose the char overload (unboxing only), the second call will choose the int version of method. Variable ch of type Character will be passed into method as int argument because of the applied unary plus.

like image 44
Peter Perháč Avatar answered Sep 24 '22 03:09

Peter Perháč