4

I was writing this code in eclipse, it war written, and the result is 3d.

public static void main(String[] args) {
    double a = 5d + + + + + +-+3d;
    System.out.println(a);
}
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
itjun
  • 49
  • 1

2 Answers2

6

Your expression can be rewritten as

(5d) + (+ + + + +-+3d)

Where the first + is the addition operator applied to two operands.

All the + and - in + + + + +-+3d are unary operators that add up to the sign of the number 3d.

In the end, your arithmetic expression is

5d + (-3d)

Which returns 2d. You can apply multiple unary operators to an expression, as in the following examples:

+ - - 2 // 2
- + + 2 // -2
ernest_k
  • 44,416
  • 5
  • 53
  • 99
4

The output of that code is 2.0, and that is because all but the first + are unary plus/minus operators.

+3d is same as 3d
-+3d is then same as -3d
+-+3d is then same as -3d
...
+ + + + +-+3d is then same as -3d
5d + + + + + +-+3d is then same as 5d + -3d
Which is same as 5d - 3d
So result is 2d
Which prints as 2.0

Andreas
  • 154,647
  • 11
  • 152
  • 247