Jump to content

Checking If a Java Array Contains a Value


Linux Hint

Recommended Posts

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:

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

Screenshot_2-6.png

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:

Screenshot_3-6.png
The following output is printed if C++ is taken as the input value that exists in the array values:

Screenshot_4-5.png

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:

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

Screenshot_6-3.png

Conclusion

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

View the full article

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...