Difference between new type [0] and null - java

What's the difference between

type[] a = new type[0]; 

and

 type[] a = null; 

Are any forms used in any memory? Are there any similarities / differences?

+6
source share
2 answers

The first ( new type[0] ) will actually create an array object (and therefore take up memory). You can use an array object (size 0), for example, to get its length or iterate over it, but you, of course, cannot access any of its elements. That way, you can pass it to any function that makes no assumptions about the length of the array (but the correct checks are performed instead), and it will work.

The second ( null ) does not create any object. You will get an exception if you try to access any member.

+8
source

You need 3 steps to create an object.

  • Decleration enter []; → Deviation. When you declare an object, you are not taking up memory for the instance, but taking up some memory for the reference.

  • Instances To do this, you need a "new" keyword. When you instantiate an object, you are taking up memory.

  • Initialization For this you need a constructor, Like → type A [] = new A [size]; What is it.

-1
source

Source: https://habr.com/ru/post/989663/


All Articles