0

I have some trouble to understand this part of code:

for (int i = 0; i < nums.length - 2; i++) {
        if (i != 0 && nums[i] == nums[i - 1]) continue;


    

When we started at the first iteration "i=0" :

    "nums[0-1] -> nums[-1] ", 

is not an Index Out of Bounds? Because the program works, but I don't know why this don't give a IndexOutOfBounds.

user207421
  • 305,947
  • 44
  • 307
  • 483

2 Answers2

-1

In the if check first you’re checking whether I!=0 and when I=0 this is false so it doesn’t go to the second check which could cause an out of bounds error.

Instead it directly goes to the next iteration where I=1 and it doesn’t throw an out of bounds

Also I’d say instead of starting from I=0 and adding the I!=0 check, why don’t you just put “int i=1” Iin the for loop. Then you can remove the first check

Shubham Periwal
  • 2,198
  • 2
  • 8
  • 26
-1

On the first iteration, the first Boolean expression yields false (because i!=0 is false). So the interpreter does not evaluate anything on the other side of the && operator. And it never tries to use the negative array index.

Howlium
  • 1,218
  • 1
  • 8
  • 19