Published 26 Oct, 2022

Java - Java check if array[] item exists

Category Java
Modified : Nov 27, 2022
29

I am downloading some data into a String array. Let's say ImageLinks. How do I check if a item in array exist?

I am trying

if(ImageLinks[5] != null){}

but it gives me ArrayIndexOutOfBoundsException. (Because there are really no 5 link in the array)

Answers

There are 4 suggested solutions here and each one has been listed below with a detailed description. The following topics have been covered briefly such as Arrays, Java. These have been categorized in sections for a clear and precise explanation.

68

To prevent the ArrayIndexOutOfBoundsException, you can use the following:

if(ImageLinks.length > 5 && ImageLinks[5] != null)
{
    // do something
}

As the statements in the if are checked from left to right, you won't reach the null check if the array doesn't have the correct size.

It's quite easy to generalise for any scenario.


54

Make sure array is of that length before doing lookup

if(ImageLinks.length > 5 && ImageLinks[5] != null){}

26
if (ImageLinks != null && Stream.of(ImageLinks).anyMatch(imageLink-> imageLink != null)) {
//An item in array exist
}

23

Write a static function

public static boolean indexInBound(String[] data, int index){
    return data != null && index >= 0 && index < data.length;
}

Now, give it a call in your code

if(indexInBound(ImageLinks, 5) && ImageLinks[5] != null){
   //Your Code
}