0

i am a java begineer and my confusion is:
in c++ we have seen that we can initiliaze the array just by writing this-
int a[5];
but in java we need new operator for array initilzation as-
int a[]=new int[5];
plz explain me in detail the reason for this???

5
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by lisaroy1
0

int a[] (or int[] a ) defines a variable a that is a reference (like a pointer) to an array of ints. It's initial value is "null" - ie it does not contain an actual reference
new int[5] allocates memory in the heap for an array of 5 ints
so
int[] a = new int[5];
creates an array of 5 ints, creates an int array reference, and sets that reference to point to the array.

0

int [] A does the initialization but using a new operator like this int [] A = new int[x],creates an object that will serve as a reference to the memory location of the array,using the array without the new operator will give an error message of null pointer exception

0

In case you happen to have the values at compile time and want to hard-code them, you can also do this:

int[] a = {1,2,3,4,5};

Which creates the array on the right-hand side and assigns it to the array a.

But I can't think of a lot of occasions when I've needed something like that.

0

In java there are two steps first is declaring the array and the second is to initiliase the array.
So in first step the array is only declared.and in the Secon step it is getting the actual memory with the help of new keyword

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.