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
}
}
This approach is great when you need to initialize an array in Java dynamically based on conditions or calculations.