Reputation: 541
What is the difference between
type[] a = new type[0];
and
type[] a = null;
Do either forms occupy any memory ? Are there any similarities / differences ?
Upvotes: 6
Views: 544
Reputation: 1
You need 3 steps to create an object.
Decleration type A[]; -> A decleration. When you declare an object, you do not occupy any memory for the instance but occupy some memory for the reference.
Instantiation To do this,you need 'new' keyword. When you instantiate an object,you do occupy memory.
Initialization To do this you need constructor, Like -> type A[] = new A[size]; That's it.
Upvotes: -1
Reputation: 2982
The first one (new type[0]
) will actually create an array object (and therefore occupy memory). You can use the (0-sized) array object, for example to get its length or iterate over it, but you can, of course, not access any of its elements. So you can pass it to any function that doesn't make assumptions about the array's length (but does the proper checks instead) and it will work.
The second one (null
) doesn't create any object. You will get an exception, if you try to access any member.
Upvotes: 8