简体   繁体   中英

How does Java handle an out-of-bound array index in a while-loop condition?

I'm following a tutorial for a two-pointer implementation (solution for 3Sum essentially) and I'm confused about the second while-loop in this search method:

  private static void searchPair(int[] arr, int targetSum, int left, List<List<Integer>> triplets) {

    int right = arr.length - 1;
    
    while (left < right) {
        int currentSum = arr[left] + arr[right];

        if (currentSum == targetSum) { // found the triplet
            triplets.add(Arrays.asList(-targetSum, arr[left], arr[right]));
            left++;
            right--;

            while (left < right && arr[left] == arr[left - 1])
              left++; // skip same element to avoid duplicate triplets
            while (left < right && arr[right] == arr[right + 1])
              right--; // skip same element to avoid duplicate triplets
      
    } else if (targetSum > currentSum)
        left++; // we need a pair with a bigger sum
      else
        right--; // we need a pair with a smaller sum
  }
}

while (left < right && arr[right] == arr[right + 1])

Won't this be an out of bounds exception since right is the last index, so right + 1 will be out of bounds? But the code runs just fine so I'm confused. How does Java handle this case?

Java handles the && in order. Meaning that if left < right fails (ie it's the last element), then the second part of the conditional is not evaluated at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM