Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking the size or length of a string array in java

Tags:

java

I have this

String p[] = null;

I need to check whether its size/length is null or not. Something like

if (p.length == null)

But it does not work.

like image 767
athresh Avatar asked Dec 06 '22 22:12

athresh


1 Answers

You cannot check length of null. Also, length returns an int which can never be null. Just do

if (p == null) {
    // There is no array at all.
} else if (p.length == 0) {
    // There is an array, but there are no elements.
}

Or just instantiate it instead of keeping it null.

String[] p = new String[0];

Then you can do:

if (p.length == 0) {
    // There are no elements.
}   

See also:

  • The Java Tutorials - Arrays
like image 127
BalusC Avatar answered Dec 10 '22 13:12

BalusC