A-ar
A-ar

Reputation: 76

Why does this simple code throw ArrayIndexOutOfBoundsException?

This is just a dummy code. I fail to understand what is wrong as I am new to JAVA.

I have already referred: What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? The answers there only pertain to using wrong length indices.

Code:

class abc{
    static int n;
    static int[] arr=new int[n];
    static void print_arr(){
        for(int x: arr) System.out.print(x+" ");
    }
}
class Main {
    public static void main(String[] args) {
        abc.n=5;
        for(int i=0;i<abc.n;i++){
            abc.arr[i]=10;
        }
        abc.print_arr();
    }
}

I want this code to print 10 five times.

Upvotes: 0

Views: 78

Answers (2)

Karthick Kumar
Karthick Kumar

Reputation: 27

class abc
{
    static int n=5;
    static int[] arr=new int[n];
    static void print_arr()
    {
        for(int x: arr) System.out.print(x+" ");
    }
}
class Main 
{
    public static void main(String[] args) 
   {
        for(int i=0;i<abc.n;i++)
        {
            abc.arr[i]=10;
        }
        abc.print_arr();
    }
}

In your case ArrayIndexOutOfBounds exception occurs because you are trying to initialize the array by a variable which has not been initialized yet. So either initialize n with a value before array initialization or use dynamic sized array.

Upvotes: 0

user3187479
user3187479

Reputation: 84

One possible way.

class abc{
static int n;
static int[] arr;
static void init(int size) {
    arr=new int[size];
}
static void print_arr(){
    for(int x: arr) System.out.print(x+" ");
} }


class Main {
public static void main(String[] args) {
    abc.n=5;
    init(abc.n);
    for(int i=0;i<abc.n;i++){
        abc.arr[i]=10;
    }
    abc.print_arr();
} }

Better way

class ABC{
 private int size;
 private int[] arr;

ABC(int n) {
    size = n;
    arr = new int[n];
}   

public void print_arr(){
    for(int x: arr) 
    System.out.print(x+" ");
}

public int getSize() {
    return size;
}

public int[] getArray() {
    return java.util.Arrays.copyOf(arr,arr.length);
}

public void setArray(int [] array) {
    arr = array.clone();
} }


class Main {
public static void main(String[] args) {

    int size = 5;
    ABC abc = new ABC(size);

    int [] array = new int[size];

    for(int i=0;i<abc.getSize();i++){
        array[i]=10;
    }
    abc.setArray(array);

    abc.print_arr();
} }

Upvotes: 2

Related Questions