In Java, you have to differentiate between primitive types and reference types.
When an array is initialized with new <sometype>[size]
, all its elements are set to a default value. For int
, long
, byte
etc, the value is 0. So you can run an average function on such an array, and you will get an average of 0.
If the type is boolean, the initial value is false
.
If the type is any object type (class), including the well-known types such as String
, Integer
, etc, the default values are all nulls.
So basically, when you create an array, if it's of a primitive type, then you can say, by your definition, that its length is its "effective size", because 0
or false
are legitimate values.
If it's of a reference type, then when you create it, its effective size - by your definition - is zero, because there are no non-null elements.
However, using new
is not the only way to initialize an array. You can, for example, use something like:
Integer[] intObjects = { 5, 17, 32 };
Note that this is an array of type Integer
, which is a reference type, rather than int
, the primitive type. If you had initialized it with new Integer[3]
you would have had all nulls. But when you initialize it as I showed, it contains references to three Integer
objects containing the numbers 5, 17 and 32 respectively. So you can say its effective size is the same as its length.
Note, however, that it's also legitimate to write something like:
Integer[] intObjects = { 5, null, 32 };
With all that in mind, the answer to the question "How do I know how many null values are in the array" is:
- If the array is of primitive type, there are no null values. It contains legitimate values, even if they are zero/false.
- If the array is of a reference type, and you initialized it with
new
, then all its elements are null.
- If the array is of a reference type, and you initialized it with
{...}
, or assigned values since its initialization, you have no way to know how many nulls are in it, except by looping and counting.