Check if an element exists in an array in Java

We want to check that a value exists in an array and retrieve its position if possible. You can choose one of three methods:
  • Browse the array and compare all the boxes with the input value and both.
  • The contains()
  • The method  BinarySearch()

1) Search for an element by browsing the array

In this example, we create a function exists() which returns the position of the value you are looking for if the array exists, otherwise it returns -1 and displays a message indicating that the array does not have this value.

public class Test {

public static void main(String[] args) {
int T[]={1, 5, 2, 22, 14, 3, 18, 52, 40, 88, 73, 27};
int valrech=22;
int position = exists(T, valrech);
if(position!=-1)
System.out.println(valrech+" is in the "+position" position);

}

static int exists(int T[], int val){
for(int i = 0 ; i< T.length; i++){
if(val==T[i])
//return current position
return i;
}
System.out.println("The value you are looking for does not exist");
return -1;
}
}
Output

22 is in the 3
The comparison of Strings is done with the equals() method and not "==". Read the articleHow to compare two Strings in java.

2) Check if the element exists in the array

This method only tests the existence of the element. In this example, the following code can compare both the string and int types. To be able to use the contains, you need to convert the entire array to a string array with toString(T).

import java.util.Arrays; 

public class Test {

public static void main(String[] args) {
int T[]={100,150,180,220,240};
System.out.println(contains(T, "220"));

}

static public boolean contains(int[] T, String val) {
return Arrays.toString(T).contains(val);
}
}
Output

true
Why contains() supports the String type but not the int type? Simply because int is a primitive type and String becomes an object after instantiation and can be used in contains(Object o) which only looks for objects.

We can propose the solution of converting int to an Integer object with the method Integer.valueOf(T[i]), otherwise the Integer object is used from the beginning. This code shows the difference between the two:

import java.util.Arrays; 

public class Test {

public static void main(String[] args) {
int T[]={10,14,28,201,280};
Integer[] T2 = {10,14,28,201,280};
//array int
System.out.println(Arrays.asList(T).contains(28));
//array Integer
System.out.println(Arrays.asList(T2).contains(28));
}
}
Output

false
true

3) Find a value with the BinarySearch method

This method is generic since it accepts all types: integer, float, char, double, boolean, short,etc.

import java.util.Arrays; 

public class Test {
public static void main(String[] args) {
int T[]={'a','b','c','d','e','f'};
System.out.println("The value you are looking for is in
the position "+Arrays.binarySearch(T,'d'));
}
}
Output:

The value you are looking for is in the 3