Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify is an array of cells is null in java?

Tags:

java

I'm trying to make an insertion into an array of cells, but only when that cell is empty.

In my case, that would mean null because I initialize an empty char array, and I want to insert only when the cell is empty (null).

The test: if grid[i][j] == null does not work, I get "== cannot be applied to 'char', null".

What is the proper way to do this?

like image 853
momodjib Avatar asked Nov 01 '19 21:11

momodjib


People also ask

How to check if an array is null in Java?

Surelly to check if an array is null one would say (array == null) There's a key difference between a null array and an empty array. This is a test for null. int arr [] = null; if (arr == null) { System.out.println ("array is null"); }

How to define an empty array in JavaScript?

There is no standard definition to define an empty array. We will assume an array is empty if Array is null. Array has no elements inside it. All the elements inside the array are null. To check if an array is null, use equal to operator and check if array is equal to the value null.

Is it possible to test if an array is empty?

It doesn't matter that the array itself is empty. The null test in your post would only evaluate to true if the variable k didn't point to anything. I tested as below. Hope it helps. Integer [] integers1 = new Integer [10]; System.out.println (integers1.length); //it has length 10 but it is empty.

Does array have a default value in Java?

However, java/c# are more/less same. If you instantiate a non-primitive type (array in your case), it won't be null. In this case, the space is allocated & each of the element has a default value of 0. It will be null, when you don't new it up.


2 Answers

The "null" character is '\0', so you can compare if grid[i][j] == '\0'.

The literal null is for reference types, which char is not.

like image 199
kaya3 Avatar answered Nov 10 '22 23:11

kaya3


Primitive arrays such as your char[][] can't contain null. Only object arrays can hold nulls. You could convert your array to Character[][] instead.

Thanks to autoboxing your existing code should work just fine, but now you can actually put nulls in it.

like image 22
Kayaman Avatar answered Nov 10 '22 22:11

Kayaman