Java Array Initialization Error

How do I initialize an array in Java?

I’m trying to initialize an array in Java using the following approach:

public class Array { int data[ ] = new int[10];

/** Creates a new instance of Array */
public Array() {
    data[10] = {10,20,30,40,50,60,71,80,90,91}; 
}     

}

However, NetBeans throws an error at this line:

data[10] = {10,20,30,40,50,60,71,80,90,91};

How can I properly initialize an array in Java and fix this error?

Alright, let’s clear this up! The simplest and most straightforward way to initialize an array in Java is to declare and assign values in one step. This avoids unnecessary complexity and is perfect when you already know the values.

public class Array {
    int[] data = {10, 20, 30, 40, 50, 60, 71, 80, 90, 91}; 

    public static void main(String[] args) {
        Array arr = new Array();
        System.out.println(arr.data[0]);  // Output: 10
    }
}

:white_check_mark: This approach is clean, efficient, and works best when values are predefined. No constructor is needed—just declare and go!

Now, if you prefer initializing the array inside the constructor (maybe because the values come from somewhere else later), you need to do it properly. The original code had two issues:

  1. You can’t use {} directly in an assignment.
  2. data[10] is out of bounds (since arrays in Java are zero-indexed).

Here’s how you initialize an array in Java inside the constructor:

public class Array {
    int[] data;

    public Array() {
        data = new int[]{10, 20, 30, 40, 50, 60, 71, 80, 90, 91};  
    }

    public static void main(String[] args) {
        Array arr = new Array();
        System.out.println(arr.data[0]);  // Output: 10
    }
}

:white_check_mark: Now, the array is initialized correctly within the constructor, keeping things flexible if you want to modify values later.

But what if you don’t have predefined values? Maybe you need to generate them dynamically? In that case, using a loop is a smarter move.

public class Array {
    int[] data = new int[10];

    public Array() {
        for (int i = 0; i < data.length; i++) {
            data[i] = (i + 1) * 10;  // Assigning values 10, 20, 30, ... dynamically
        }
    }

    public static void main(String[] args) {
        Array arr = new Array();
        System.out.println(arr.data[0]);  // Output: 10
    }
}

:white_check_mark: This approach is great when you need to initialize an array in Java dynamically based on conditions or calculations.