0

I want to reverse an int array in java and this is the code but it throws an error arrayOutOfBound exception.

class reverse_number {
    public static void main(String[] args) {
        int ar[]={1,3,4,2};
        int ar1[]=new int[4];

        for(int i=0;i<ar.length;i++) {
            ar1[i++]=ar[ar.length-1];
        }

        for(int i=0;i<ar1.length;i++) {
            System.out.print(ar1[i]);
        }
    }
}
Andreas
  • 2,300
  • 10
  • 19
  • 23
Sam
  • 27
  • 5

3 Answers3

2
public static void main(String[] args){
    ...
    int reveArr[] = new int[arr1.length];

    for(int i = 0 ; i <arr1.length;i++){
        reveArr[i] =arr1[arr1.length-i-1];
    }
    ...
}

You are incrementing i twice. When you try to access the array using index beyond its capacity (when i is on the last iteration, and you access arr1[i++], the index you are accessing exceeds the length of arr1), it is bound to give you an ArrayIndexOutOfBoundsException.

skomisa
  • 12,583
  • 7
  • 47
  • 75
SArya
  • 43
  • 6
1

You are doing

for(int i=0;i<ar.length;i++)

then in this loop you are increment i again

ar1[i++]

This is not necessary, just use i

Scary Wombat
  • 41,782
  • 5
  • 32
  • 62
0

Please try this .

class reverse_number {
    public static void main(String[] args) {
        int ar[] = { 1, 3, 4, 2 };
        int ar1[] = new int[4];
        int count = 0;
        for (int i = ar.length - 1; i >= 0; i--) {
            ar1[count++] = ar[i];

        }
        for (int i = 0; i < ar1.length; i++) {
            System.out.print(ar1[i]);
        }
    }
}