Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a String[] index exists?

Tags:

java

I have a String[] and I would like to check if an index exists in it (such as String[3]).

How can I go about doing this?

like image 230
Liam W Avatar asked Dec 01 '25 11:12

Liam W


2 Answers

if (arr != null && i >= 0 && i < arr.length) {
  // arr[i] exists
}

If arr is an array of objects, you may also need to check whether arr[i] is null:

if (arr != null && i >= 0 && i < arr.length && arr[i] != null) {
  // arr[i] exists and is not null
}
like image 97
NPE Avatar answered Dec 03 '25 01:12

NPE


An existing index doesn't necessarily mean a non-null array entry, be careful.

String[] array = ...
int index = 3;

if(array.length > index && index >= 0)
  // it exists.
like image 25
Juvanis Avatar answered Dec 03 '25 02:12

Juvanis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!