'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?
Solution 1:[1]
Java handles the && in order. Meaning that if left < right fails (i.e. it's the last element), then the second part of the conditional is not evaluated at all.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | vjh |
