When we create a object of a classtype the new operator allocates the memory at the run time.
Say
myclass obj1 = new myclass();
here the myclass()
defines a constructur of myclass
but
int arr1[4] = new int[];
new allocates the memory but, what the int[]
does here?
New allocates the memory but, what the int[] does here?
The int[]
part simply specifies what type the newly allocated memory should have.
However, since an array can't grow dynamically, it doesn't make sense to write new int[]
(even though you've specified int[4]
in the declaration), you'll have to write it either like this
int arr1[] = new int[4];
or like this
int arr1[] = {1, 2, 3, 4};
Relevant sections in the JLS:
Your code:
int arr1[4] = new int[];
will not compile. It should be:
int arr1[] = new int[4];
putting []
before the array name is considered good practice, so you should do:
int[] arr1 = new int[4];
in general an array is created as:
type[] arrayName = new type[size];
The [size]
part above specifies the size of the array to be allocated.
And why do we use
new
while creating an array?
Because arrays in Java are objects. The name of the array arrayName
in above example is not the actual array, but just a reference. The new
operator creates the array on the heap and returns the reference to the newly created array object which is then assigned to arrayName
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With