Codi
Codi

Reputation: 541

difference between new type[0] and null - java

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

Answers (2)

M Enes Turgut
M Enes Turgut

Reputation: 1

You need 3 steps to create an object.

  1. 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.

  2. Instantiation To do this,you need 'new' keyword. When you instantiate an object,you do occupy memory.

  3. Initialization To do this you need constructor, Like -> type A[] = new A[size]; That's it.

Upvotes: -1

mastov
mastov

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

Related Questions