Can someone tell me why am I getting compilation error for explicitly setting NULL
value to an array element?
int[] a = new int[5];
a[0] = 1;
a[2] = 'a';
a[3] = null; //Compiler complains here
for (int i : a) System.out.println(i);
I am assuming because its an int array and the literal value allowed is 0
and not NULL
. Am I right?
Correct. int
is a primitive type, which means that it contains an explicit value (a number from -2^31 to 2^31-1), and not a reference, so it can't be null
. If you really need null
values, use Integer
.
Your array
int[] a
is of primitive type int
. Primitives cannot have a null
value but instead have a default value of 0. Only objects in java can have null as a value
. Primitives include: byte,short,char,int,long,float,double.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With