mardi 10 octobre 2017

Condition priority in Java

I noticed a thing that was very unclear to me. It was the priority of conditions in while loop in Java.

Let's consider this example of Insertion Sort: Link to Gist here.

Line 11: while (it >= 0 && arr[it] > tmp) {

Using this order of conditions (firstly we check if it >=0 and then if arr[it] > tmp works perfectly.

However, when I try to switch the places of these two conditions I get an unexpected result, more precisely: IndexOutOfBoundsException.

So, it seems that there are some condition priority checks and I'm not aware of them. I thought that && (and) checks both sides equally. Am I wrong? Can you explain why this happens and what is the priority of conditions?

Aucun commentaire:

Enregistrer un commentaire