Creating an Array of Objects in Java
I Am New to Java and for the Time Created an Array of Objects in Java. I Have a Class a for Example - A[] Arr = New A[4]; but This Is Only Creating Pointers...
I am new to Java and for the time created an array of objects in Java.
I have a class A for example -
A[] arr = new A[4];
But this is only creating pointers (references) to A and not 4 objects. Is this correct? I see that when I try to access functions/variables in the objects created I get a null pointer exception.
To be able to manipulate/access the objects I had to do this:
A[] arr = new A[4];
for (int i = 0; i < 4; i++) {
arr[i] = new A();
}
Is this correct or am I doing something wrong? If this is correct its really odd.
EDIT: I find this odd because in C++ you just say new A[4] and it creates the four objects.
9 Answers
This is correct.
A[] a = new A[4];
...creates 4 A references, similar to doing this:
A a1;
A a2;
A a3;
A a4;
Now you couldn't do a1.someMethod() without allocating a1 like this:
a1 = new A();
Similarly, with the array you need to do this:
a[0] = new A();
...before using it.
This is correct. You can also do :
A[] a = new A[] { new A("args"), new A("other args"), .. };
This syntax can also be used to create and initialize an array anywhere, such as in a method argument:
someMethod( new A[] { new A("args"), new A("other args"), . . } )
Yes, it creates only references, which are set to their default value null. That is why you get a NullPointerException You need to create objects separately and assign the reference. There are 3 steps to create arrays in Java -
Declaration – In this step, we specify the data type and the dimensions of the array that we are going to create. But remember, we don't mention the sizes of dimensions yet. They are left empty.
Instantiation – In this step, we create the array, or allocate memory for the array, using the new keyword. It is in this step that we mention the sizes of the array dimensions.
Initialization – The array is always initialized to the data type’s default value. But we can make our own initializations.
Must Read
Declaring Arrays In Java
This is how we declare a one-dimensional array in Java –
int[] array; int array[];Oracle recommends that you use the former syntax for declaring arrays. Here are some other examples of legal declarations –
// One Dimensional Arrays int[] intArray; // Good double[] doubleArray; // One Dimensional Arrays byte byteArray[]; // Ugly! long longArray[]; // Two Dimensional Arrays int[][] int2DArray; // Good double[][] double2DArray; // Two Dimensional Arrays byte[] byte2DArray[]; // Ugly long[] long2DArray[];And these are some examples of illegal declarations –
int[5] intArray; // Don't mention size! double{} doubleArray; // Square Brackets please!