4

I ran across this while reviewing a colleague's code. She'd left it in by accident (it used to be a String concatenation), and I assumed that it wouldn't compile. Turns out I was wrong, so I tried seeing what that operator did:

public static void main(String[] args) {
    int i = -1;
    System.out.println(String.format("%s", +i));
    System.out.println(String.format("%s", +i));
}

As far as I can tell, it does nothing, but I'm curious if there is a reason it's allowed to compile. Is there some hidden functionality to this operator? It's similar to ++i, but you'd think the compiler would barf on +i.

monitorjbl
  • 4,280
  • 3
  • 36
  • 45

1 Answers1

2

That is the plus unary operator +. It basicaly it does numeric promotion, so "if the operand is of compile-time type byte, short, or char, it is promoted to a value of type int".

Another unary operator is the increment operator ++, which increments a value by 1. The increment operator can be applied before (prefix operator) or after (postfix operator) the operand. The difference is that the prefix operator (++i) evaluates to the incremented value, whereas the postfix operator (i++) evaluates to the original value.

int i = -1;
System.out.println(+i);         // prints -1

System.out.println(i++);        // prints -1, then i is incremented to 0

System.out.println(++i);        // i is incremented to 1, prints 1
ericbn
  • 10,163
  • 3
  • 47
  • 55
  • 1
    Here is a (slightly) more detailed reference: http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.15.3 – Riccardo T. Sep 18 '14 at 14:45