-1

I am learning Java and just learned that the order in which the operations are carried out is determined by the precedence of each operator in the expression. enter image description here

According to the picture above, the ++ and -- are evaluated first, but for example:

public class StudyDemo {
    public static void main(String[] args) {
        int a = 5;
        int result = -a++;
        System.out.println(result);
    }

}

Why the result's output is -5?

ChenLee
  • 1,371
  • 3
  • 15
  • 33
  • The increment symbol (`++`) has higher priority than negative symbol (`-`). But the operator `a++` is grant value of `a` first, after that increment `a` 1 value. You may be confused with `++a` (increment `a` 1 value then grant `a`). With `a = 5`, if `result = -(a++)` will show `result = -5` and `a = 6`. But if `result = -(++a)` will show `result = -6` and `a = 6`. – Man1s Sep 30 '20 at 08:32

2 Answers2

1

a++ is a post-increment. Which means the value is first read as 5 and then incremented afterwards (a++ evaluates to 5, but as a side effect, it is incremented to 6 immediately afterwards).

So a++ evaluates to 5 inside the expression and is 6 afterwards.

Using a unitary - turns 5 into -5.

This is in contrast to the pre-increment ++a, where a is incremented first to 6, and then read.

Polygnome
  • 7,639
  • 2
  • 37
  • 57
0
int result = -a++;
  1. ++ Has highest priority so a++ happens first; But it is post increment it returns 5 here
  2. Now the Sign Operator add negative sign to 5
Shubham Srivastava
  • 1,807
  • 1
  • 10
  • 17