'int array might not have been initialized

class MyClass {
    public int[] arr;
}

public static void main(String args[]) {
    MyClass thing;
    thing.arr = new int[]{1, 2, 3, 4, 5};
}

Error: variable thing might not have been initialized

...what? I'm literally assigning it an array, why is it giving me this error?



Solution 1:[1]

Try this:

public class MyClass {
    private int[] data;

    public MyClass(int[] data) {
       this.data = data;
    }

    public int[] getData() {
       return data;
    }
}

and for your main

public static void main(String [] args) {
     MyClass myClass = new MyClass(new int[]{1, 2, 3, 4, 5});
     System.out.println(Arrays.toString(myClass.getData());
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ryan