How to check if an int array contains a number

How can I check if an array contains a number? Here’s an example:

int [] array = new int [200];
array[0] = int(random(0,200));
If(array.contains 20){


Look through the Processing resources:

This is for a simple array…

At present the first two lines are assigning a random number to the first element array[0] of the array.

Once you start to understand arrays and work with them then:

  • add a few line of code to loop through the array and display contents
  • in the loop check to see if it contains the number.
  • use println() statements strategically to assist with understanding code

Once you can work through this and have a working example there are more advanced ways to do this.



Nice question. So what we have to do here, is to go through all the numbers of the array, and check each one to see if they are equal to 20. We can do this with a loop.

for (int a = 0; a < ARRAY_SIZE; ++a)
   if (array[a] == 20)

So to visualize it:

array = { 7, 13, 20, 2 };

is the first element equal to 20?
if no, then is the second element equal to 20?
we keep doing this until an element hits 20

Hope this helps!

1 Like

For a primitive arrays you must loop through all the values and return true if they are equal.

boolean contains(int[] arr, int val) {
  for(int i=0; i<arr.length; i++) {
    if(arr[i]==val) {
      return true;
  return false;

However, for Object arrays you can use “.contains()” or a related method. Your example is a list of ints, and Processing already has this built-in: IntList.hasValue()

If you are working with Strings or floats there is StringList and FloatList. For other objects there is ArrayList, et cetera.

1 Like