0

What rules govern such unexpected behaviour?

int i1 = -+0007;
int i2 = +-0007;
System.out.println(i1);  // output: -7
System.out.println(i2);  // output: -7

    int i3 = +-+0007;   // -7
    int i4 = -+-0007;   // 7

I understand that unary sign operator is right-associative. But if minus goes first (rightmost), it seems that next plus (to the left) does not change sign from minus to plus (i.e. does nothing!). But second minus changes sign (from negative to positive).

Besides we cannot use ++ or -- anywhere in this sequence of +-+-+- (+--+ is compile error: rightmost + (or leftmost +) is wrong operand of -- operation).

Code Complete
  • 3,146
  • 1
  • 15
  • 38

2 Answers2

1

Unary - changes the sign. Unary + doesn't, it's mostly pointless, it does an unary numeric promotion, you can see here for some more details about it.

So in your first line:

int i1 = -+0007;

+ does nothing - changes to -7

Second line:

int i2 = +-0007;

- changes to -7 + does nothing

+--+ is a compile error because -- is a different operator that can only operate on a variable. Something like the following will work:

int b = 1;
int a = -++b; // increment b by 1, change the sign and assign to a
System.out.println(a); // prints -2

You can use parenthesis or add space to make +--+ compile

int i = +-(-+7); // will be equal to 7 because only the 2 `-` change the sign
int i = +- -+7;
Oleg
  • 6,124
  • 2
  • 23
  • 40
-1

It has tog do with Maths. If you multiply a negative and a positive number, the result is negative. If you multiply two negative numbers, the result is positive.

So, the - or + could also be written as:

-…: (-1) * …
+…:  (1) * …
caylee
  • 921
  • 6
  • 12
  • It is just the mathematical explanation. You could also say, `-` changes the sign, and `+` does not. – caylee Oct 28 '17 at 07:16