-3

Hi I'm beginner to java program, I'm getting one exception error in common sort array program

      public static void main(String[] args) {
    // TODO Auto-generated method stub
    int[] arr1={4,5,6,8};
    int[] arr2={5,4,2,1};
    int[] arr3={4,5,3,2};

    for(int i=0;i<=arr1.length;i++){
        for(int j=0;j<=arr2.length;j++){
           for(int k=0;k<=arr2.length;k++){

             if(arr1[i]==arr2[j] && arr2[j]==arr3[k])
             {
                System.out.println(arr3[k]);
             }

          }
       }
    }

}
samkarthick
  • 1
  • 1
  • 7

2 Answers2

0

Java has array indexed from 0 to length - 1. So instead of less than equal to operator <= you should use less than operator < in this case.

Deepansh Sachdeva
  • 1,168
  • 9
  • 16
0

The problem is in for loop condition, you have only 4 elements in array and array index start with zero so your loop must start from 0 to 3 but <= operator checks for the forth index in array which not exist so just use < so the loop terminates after evaluating last index

Digvijaysinh Gohil
  • 1,367
  • 2
  • 15
  • 30