Java

Checking If a Java Array Contains a Value

A Java array is used to store multiple numeric values or string values in a variable. Many options exist in Java to search for a particular value in an array. Using the “for” loop is the simplest way to search a numeric or string value in the Java array. However, many built-in functions exist in Java to search for a particular value in an array. The methods of checking whether a particular value exists in a Java array or not using a loop and Java built-in functions are shown in this tutorial.

Example 1: Using a “For” Loop

Create a Java file with the following code that takes an input from the user and check whether the input value exists in the array or not using the “for” loop.  An array of string values is defined in the code. A string value is taken from the user using the “Scanner” class. Then, this is compared with each value of the array. If any match is found, the iteration of the loop is stopped and a success message is printed.

//Import the Scanner module
import java.util.Scanner;
public class CheckArrayValue1 {
    public static void main(String[] args) {
       
        //Declare an array of string values
        String [] strArray = {"Java","C++","C#","VB.NET","J#"};
       
        //Declare a scanner object
        @SuppressWarnings("resource")
        Scanner lang = new Scanner(System.in);
        System.out.println("Enter a programming language name: ");
       
        //Take input from the user
           String name = lang.nextLine();
   
           //Set the variable to false
        Boolean found = false;
       
        //Iterate the loop to check each value of the loop
        for(int i =0; i < strArray.length; i++) {
            //Compare each value of the array with the input value
            if(name.equals(strArray[i]))
            {
                //Print the success message
                System.out.println("The '" + name + "' exists in the array.");
                //Set the variable to true
                found = true;
                break;
            }
        }
       
        //Check the variable to print the failure message
        if(! found)
         System.out.println("The '" + name + "' does not exist in the array.");
    }
}

 
Output:

The following output is printed if Java is taken as the input value that exists in the array values:


The following output is printed if Perl is taken as the input value that does not exist in the array values:

Example 2: Using the Contains() Method

Create a Java file with the following code that takes an input from the user and check whether the input value exists in the array or not using the contains() method.  This method returns true if the input value exists in the array. Otherwise, this method returns false.

//Import the necessary modules
import java.util.Scanner;
import java.util.Arrays;
public class CheckArrayValue2 {
    public static void main(String[] args) {
       
        //Declare an array of string values
        String [] strArray = {"Java","C++","C#","VB.NET","J#"};
       
        //Declare a scanner object
        @SuppressWarnings("resource")
       
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a programming language name: ");
       
        //Take input from the user
           String name = input.nextLine();
   
           //Check whether the value exists in the array or not by using contains() method
        boolean found = Arrays.asList(strArray).contains(name);
   
        //Set the initial value in the output variable
        String output = "The " + name;
           //Set the message to the output variable based on the found variable
        output += found ? " exists in the array.": " does not exist in the array.";
        //Print the output
        System.out.println(output);
    }
}

 
Output:

The following output is printed if PHP is taken as the input value that does not exist in the array values:


The following output is printed if C++ is taken as the input value that exists in the array values:

Example 3: Using the AnyMatch() Method

Create a Java file with the following code that takes an input from the user and check whether the input value exists in the array or not using the anyMatch() method of the “Stream” class.  This method returns true if the input value exists in the array. Otherwise, this method returns false.

//Import the necessary modules
import java.util.Scanner;
import java.util.stream.IntStream;
public class CheckArrayValue3
{
    public static void main(String[] args)
    {
       
        //Declare an array of numbers
        int [] numArray = {89, 45, 72, 67, 12, 43};
       
        //Declare a scanner object
        @SuppressWarnings("resource")
       
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a number to search: ");
       
        //Take input from the user
           int num = input.nextInt();
       
          //Check whether the value exists in the array or not by using anyMatch() method      
        boolean found = IntStream.of(numArray).anyMatch(x -> x == num);
   
        //Set the initial value in the output variable
        String output = "The " + num;
          //Set the message to the output variable based on the found variable
        output += found ? " exists in the array.": " does not exist in the array.";
        //Print the output
        System.out.println(output);
    }
}

 
Output:

The following output is printed if 45 is taken as the input value that exists in the array values:


The following output is printed if 100 is taken as the input value that does not exist in the array values:

Conclusion

Three different ways of checking whether the array contains a particular value or not are shown in this tutorial using multiple examples.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.