Not compiling cant find the error

import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
int n= sc.nextInt();
int[]arr=new int[n];
for(int i=0;i<arr.length;i++){
arr[i]=sc.nextInt();
}
Insertionsort(arr);
display(arr);
}
public static void display(int[]arr){
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
public static void Insertionsort(int[]arr){
for(int counter=1;counter<=arr.length-1;counter++){
int val= arr[counter];
int j= counter-1;
while(arr[j]>val&&j>=0){
arr[j+1]=arr[j];
j–;
}
arr[j+1]=val;
}
}
}

@Shivam_balwani,

Conditions are evaluated left to right.

Initially, for case j=-1 , your code wasn’t evaluating the second condition because the first one was throwing an ArrayIndexOutOfBoundsException exception.

			while (arr[j] > val && j >= 0) {

In the above condition, in case j=-1, arr[-1]>val will be evaluated first and that will give you an OutOfBoundsException run error.

However when you switched the conditions like this:

			while ( j >= 0 && arr[j] > val ) {

then for the same case ( j=-1 ), since first condition becomes false , then regardless of the second value, the whole condition will always be false (because its AND operator); and so the second condition won’t be evaluated and hence no exception in this case.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.