Getting an error of out of bound in main function

public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = null;// declaring the array
a = new int[5];// blocking the space
a[0] = 1;
a[1] = 5;
a[2] = 10;
a[3] = 15;
a[4] = 20;
int j;
for(int i=0;i<=4;i++) {
for(j=4;j>=0;j++) {
int b =a[i];
a[i]= a[j];
a[j] = b;
System.out.println(a[i]);
System.out.println(a[j]);
}
}
}
}

@rishabh.chhabra10,
In:

for(int i=0;i<=4;i++) {
for(j=4;j>=0;j++) {

You have used j++. At the start j = 4, after increment it becomes 5. Hence out of bounds.

Use j-- instead of j++

still not getting the right answer

i am not able to understand swap from this video too confusing, pls explain

@rishabh.chhabra10,
Instead of swapping the elements you are restoring them in the same order as well.

Initial array: 1, 5 , 10 , 15, 20

Now in the for loop:
when i = 0,
and we start from j = 4:

b = a[0] = 1
a[0] = a[4] and a[4] is 20. Hence, a[0] = 20
a[4] = 1
Array becomes: 20, 5, 10, 15, 1

Now when j=3:
b = a[0] = 20
a[0] = a[3] and a[3] is 15. Hence, a[0] = 15
a[3] = 20
Array becomes: 15, 5, 10, 20, 1

And so on. But if you stop and loop, at j=3, the element is not swapped with a[1], instead it is swapped with a[0].

@rishabh.chhabra10,

In the swap function we pass arr, i, j. We swap index i and j. Now in the swap method we pass reference of the array and swap index i and j. As soon as it returns back to the main method, the changes are made in the original array.
Example:
Array a: 1 2 3 4 5
Swap (a,0,2)
Now before entering swap function a will be: 1 2 3 4 5
After swap function a will be : 3 2 1 4 5
The changes will be made in the current array.

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.