Clarification regarding Postfix Increment Operator ++: java

int i = 0;
boolean b = true;
System.out.println(b && !(i++ > 0))

When I compile the above code, I return true.

But how can this be, since the second part of the argument (since b is already true) basically translates into

(0 + 1 > 0) => (1 > 0)

which should return true. Then the statement will be true && falsethat false.

What am I missing?

+4
source share
5 answers

Java behaves correctly :)

i++

This is a postfix .

He generated the result, and then increased this value later.

!(i++ > 0) // now  value is still zero

i++will use the previous valueof i, and then it will be increment.

When you use ++, he likes

temp=i;
i += 1; 
i=temp;     // here old value of i.

Postfix Increment Operator ++ language specification

1 , .......

postfix - .

++i, ,

++

- .

+11

++i, . i++ .

+3
b && !(i++ > 0)

i++ - , 0

0>0 false

b && 1 ( !(0) 1)

, .

+2
source
i++

increment occurs after line execution so you better keep

++i
+1
source

You can see how the ++ operator works in the following example:

public static void main(String[] argv) {
    int zero = 0;
    System.out.println(zero++);
    zero = 0;
    System.out.println(++zero);
}

Result: 0 1

+1
source

All Articles