Array isEmpty

Hi

I am using a normal Array not util.collections

String[] animals = { "bear", "cougar", "wolverine"};

I have two questions. How to find array is empty? How to intialize array as null(without any elements).

Thanks
basiranaAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
Peter KwanConnect With a Mentor Analyst ProgrammerCommented:
1. You can check whether the array is null or the array's length is zero.

e.g.
boolean isEmpty(String[] array) { return array == null || array.length == 0; }

2. To initialize array as null, just set it as null.
String[] array = null;
0
 
basiranaAuthor Commented:
But for this I need to create a method isEmpty(String[] array).
Is there anyway we can check inside if condition and find.

Thanks for ur reply.
0
 
Peter KwanAnalyst ProgrammerCommented:
You can just copy the condition to your if statement. Then you don't need the method.

i.e.
if (array == null || array.length == 0)
   // array is empty
else
  // array is not empty
0
 
Peter KwanAnalyst ProgrammerCommented:
of course you need to substitute "array" with your variable. In your example:

if (animals == null || animals.length == 0)
   // for empty case
else
  // for not empty case
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.