Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the new operator do when creating an array in java?

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?

like image 697
Radheshyam Nayak Avatar asked Dec 29 '22 06:12

Radheshyam Nayak


2 Answers

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:

  • 15.10 Array Creation Expressions
  • 10.6 Array Initializers
like image 96
aioobe Avatar answered Jan 12 '23 00:01

aioobe


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.

like image 26
codaddict Avatar answered Jan 11 '23 22:01

codaddict