ncw - 1 year ago 80

Java Question

This is more of a theoretical question to understand Java's evaluation of arithmetic operations. Since

`+`

`-`

`+`

`-`

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

int a = 1;

int b = 2;

System.out.println(a+-b); // results in -1

System.out.println(a-+b); // results in -1

System.out.println(a+-+b); // results in -1

System.out.println(a-+-b); // results in 3

System.out.println(a-+-+b); // results in 3

System.out.println(a+-+-b); // results in 3

System.out.println(a-+-+-b); // results in -1

System.out.println(a+-+-+b); // results in 3

}

From the Java 8 Language Specification (ยง15.8.2):

The binary + operator performs addition when applied to two operands of numeric type, producing the sum of the operands.

The binary - operator performs subtraction, producing the difference of two numeric operands.

[...]

Addition is a commutative operation if the operand expressions have no side effects.

Integer addition is associative when the operands are all of the same type.

What I also noticed, is that everytime the #operators is even, the result is the same and the order doesn't matter.

But when the #operators is odd, this doesn't necessarily influence the result. E.g. in the following two expressions there is one more

`-`

`+`

`System.out.println(a-+-b); // results in 3`

System.out.println(a-+-+-b); // results in -1

With all that information I still don't see the pattern or the way how this works.

Answer Source

In math, how would you evaluate this?

```
a - + - b
```

Adding some brackets helps:

```
a - (+ (-b))
```

We can do this, because this doesn't violate the rules of precedence.

Then we can start reducing: `+ (-b)`

is really `-b`

, and `a - -b`

is really `a + b`

, so the result is `1 + 2 = 3`

.

Let's see the second one:

```
a - + - + - b
a - (+ (- (+ (-b))))
a - (+ (- (-b)))
a - (+ b)
a - b
1 - 2 = -1
```

So simple rules of math work naturally.