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?
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With