Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

-​->-​- operator in Java

I was wondering, what does the -->-- operator do in Java?

For example, if I have the following code:

int x = 3;
int y = 3;
if (x -->-- y) {
    return true;
}

This always returns true.

Thank you!

like image 564
MarkusWillson Avatar asked Nov 30 '14 03:11

MarkusWillson


People also ask

What does << mean in Java?

Left shift operator shifts the bits of the number towards left a specified number of positions. The symbol for this operator is <<.

What is i += 2 in Java?

Using += in Java Loops The += operator can also be used with for loop: for(int i=0;i<10;i+=2) { System. out. println(i); } The value of i is incremented by 2 at each iteration.

Is a _ operator in Java?

Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.


2 Answers

In Java, -->-- is not actually an operator.

What you wrote is actually if ((x--) > (--y)).

And, as we know from this answer, the --y is predecrement, while the x-- is postdecrement, so therefore, this is basically if (3 > 2), which always returns true.

like image 181
416E64726577 Avatar answered Oct 16 '22 10:10

416E64726577


Positcrement and preicrement are very similar operators. Java's bytecode gives a better understanding. Each of them consists of two operations. Load variable and increment it. The only difference is in the order of this operations. If statement from your case is compiled this way:

 4: iload_1               //load x
 5: iinc          1, -1   //decrement x
 8: iinc          2, -1   //decrement y
11: iload_2               //load y
12: if_icmple     23      //check two values on the stack, if true go to 23rd instruction

When JVM comes up to an if statement it has 3 and 2 on the stack. Line 4 and 5 are compiled from x--. Lines 8 and 11 from --y. x is loaded before increment and y after.

BTW, it's strange that javac does not optimize out this static expression.

like image 29
Mikhail Avatar answered Oct 16 '22 10:10

Mikhail