Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly setting NULL value to an array element

Tags:

java

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?

like image 883
UnderDog Avatar asked Aug 18 '13 07:08

UnderDog


2 Answers

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.

like image 127
chrylis -cautiouslyoptimistic- Avatar answered Oct 17 '22 18:10

chrylis -cautiouslyoptimistic-


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.

like image 20
rocketboy Avatar answered Oct 17 '22 18:10

rocketboy