0

Getting java.lang.ArrayIndexOutOfBoundsException while trying to find duplicate number in an array in Java.

Here is the code:

public class FindDuplicateNumberInArray {
    public static void main(String[] args) {
        int arr[] = { 11, 24, 65, 1, 111, 25, 58, 95, 24, 37 };
        Arrays.sort(arr);
        String sortedArray = Arrays.toString(arr);
        System.out.println(sortedArray);

        for (int i = 1; i < arr.length; i++) {
            if (arr[i] == arr[i + 1]) {    
                System.out.println("Duplicate element from teh given array is = " + arr[i]);
            }
        }
    }
}
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • OP - Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at com.onejava.practice.FindDuplicateNumberInArray.main(FindDuplicateNumberInArray.java:19) [1, 11, 24, 24, 25, 37, 58, 65, 95, 111] Duplicate element from teh given array is = 24 – Madhur Palsokar Aug 19 '19 at 10:55
  • `i` will eventually reach the last index in your array, so `arr[i + 1]` will try and access an index outside of your array. Make your loop run to `arr.length-1`, such that the max value `i` will ever get to is the 2nd last index, allowing `arr[i+1]` to be a valid index – Nick Parsons Aug 19 '19 at 10:56
  • 1
    Since you're starting `i` from 1, it would make more sense to compare `arr[i]` with `arr[i-1]`. – khelwood Aug 19 '19 at 10:57

2 Answers2

0
public class FindDuplicateNumberInArray {
    public static void main(String[] args) {
        int arr[] = { 11, 24, 65, 1, 111, 25, 58, 95, 24, 37 };
        Arrays.sort(arr);
        String sortedArray = Arrays.toString(arr);
        System.out.println(sortedArray);

        // for (int i = 1; i < arr.length; i++) {
        //    if (arr[i] == arr[i - 1]) {    

        for (int i = 0; i < arr.length-1; i++) {
            if (arr[i] == arr[i + 1]) {    
                System.out.println("Duplicate element from the given array is = " + arr[i]);
            }
        }
    }
}

To check for a duplicate number, you are running the for loop to last element(say nth position), but your if condition checks the last element with (n+1)th element, which doesn't exist. And also, you need to check the 1st element too, so say i=0. Or you can just change the if (arr[i] == arr[i + 1]) condition to if (arr[i] == arr[i - 1])

0

You have a very basic IndexOutOfBounds-Exception there. When accessing arrays, you have to provide an index. If that index is greater than array.length - 1, which is the last accessible index, you get an out of bounds exception. The same is true for lists.

Because you compare the current (i) value to the next one (i + 1), you run out of bounds, because you count to i < arr.length. This means when i == arr.length - 1 you still add 1 to i, which is equal to arr.length, which is more than arr.length - 1.

TreffnonX
  • 2,924
  • 15
  • 23