| Author |
size of two dimensional arrays with null value
|
Madhu Mk
Greenhorn
Joined: Mar 07, 2007
Posts: 24
|
|
Hello Ranchers, Could any one please assist me in how to check whether a given two dimensional aray is empty or with value.. Eg: int[][] yearsArrData; for this array which is possible 1) yearsArrData.length == 0 2) yearsArrData == null Thanks in advance.. Regards, MK
|
Regards,
Madhu K
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
You are nearly there. If you get array.length == 0 then you know you have an array which does actually exist, but contains 0 elements. If you have array == null as true then you have an array which doesn't exist (null). Be sure to check for null before you check 0 length, otherwise you might get a NullPointerException.
|
 |
Madhu Mk
Greenhorn
Joined: Mar 07, 2007
Posts: 24
|
|
Hi Campbell Do mean empty arry means no existence of array object or any array with no elements - please confirm my understanding. So if I want to check any array to be empty, always it is mandatory that before checking its length I have to check for null value ?. DO there is no single option to check the same. Cheers, K Madhu
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
By "empty array" I meant one which is not null but contains no elements, ie array.length is 0, same as a zero-length array. "Null" array means one which doesn't exist ie array == null returns true. No, you can't check for null and length 0 in one step, but you can writeIt is not essential to check for null values, but your original post did suggest you might have null arrays; then you always want the null check first. I hope that helps. CR
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
|
|
Originally posted by K Madhu: int[][] yearsArrData;
Assuming this is a field, at this point imagine you haveNow, like any field which has been declared the variable points to null (or 0/false for primitive types). So yearsArrData == null returns true. System.out.println(yearsArrData.length); throws a NullPointerException. You now have a zero-length array which contains 0 number of zero-length int arrays. So NOW yearsArrData == null returns false. System.out.println(yearsArrData.length); prints 0. [edit]Minor spelling correction[/edit] [ February 06, 2008: Message edited by: Campbell Ritchie ]
|
 |
 |
|
|
subject: size of two dimensional arrays with null value
|
|
|