How to check if Array contains given Number or String in Java [ Linear Search vs Binary Search]

Hello guys, one of the common coding questions from Java interviews is how to test if an Array contains a certain value or not? This is a simple question, but sometimes interview pressure makes candidates nervous. In this article, you'll learn how to solve this problem using different approaches. Since an array in Java doesn't have any inbuilt method for searching values, interviewers prefer to ask this question, to see how a candidate deals with such a situation. If you have good knowledge of Java API, then you will immediately come to know that there are alternatives available like using the binarySearch() method of Java Java .util.Arrays class or taking advantage of ArrayList contains method by first converting your array to ArrayList.

If you come up with those solutions, the Interviewer will surely ask you to write down a method to search an element in an array without using any library method. For that, you need to remember your Data structure and algorithm classes. You can easily solve this question if you know the linear search or binary search algorithm.

Linear search is very simple to implement, all you need to do is loop through the array and check each value if that is the one or not.

Binary search is a little tricky but not too difficult either, the recursive solution is very natural as well. In this tutorial, though I have given two solutions, one is using ArrayList, and the second is using linear search, leaving binary search an exercise for you. But you must remember to sort the array before using binary search.

That's where a good knowledge of essential Data Structures and Algorithms comes to the rescue. I strongly suggest every Java developer brush up on their Data structure and algorithm skills before going for any kind of programming interview. If you need a resource, I recommend Data Structures and Algorithms: Deep Dive Using Java course by Tim Buchalaka on Udemy.

It's very affordable and covers all essential data structures like the array, linked list, binary tree, hash table, stack, queue, and others.




How to check if an array contains a given value in Java?

To give you some more idea of the problem, let's see an example first; suppose you have a String[] with values like so:

public static final String[] names = new String[] {"Java","JEE","Scala","C++"};

Given the String name, you need to return true or false, depending upon whether names contain that value or not. By the way, here is a full example of how to search a number on an integer array and searching for a name on String array, in case you need any help.

This example contains two methods isExists() and contains(), which returns true if the value is present in the array. The first method uses contains() method of ArrayList by first converting given an array to ArrayList, while the second method simply uses a linear search algorithm to search on a Java array.

By the way, to make the question more challenging, I usually asked the candidate to write a parametric method using generic so that it will work for any type of object array in Java. If you are interested, you can try solving that version as well.

In case, if you are not familiar with Generics and writing Parametric class and methods in Java then I suggest you join a comprehensive Java course like The Complete Java Masterclass on Udemy to learn Generics better. It's very important for writing production-quality Java code.


How to test if an Array contains a value in Java - Linear Search





Java Program to Search String or Integer in Given Array

Without wasting any more of your time, here is our complete Java program to search any given String or integer value in the given array. If you are using Eclipse IDE, just copy-paste the code and run it, you don't need to create a Java source file, Eclipse will take care of that, provided you have selected a Java project.



import java.util.Arrays;
/**
* Java Program to check if an array contains a value or not. Basically this program tells you
* how to search for an element in array, it could be an integer number or String value. 
*
* @author Javin Paul
*/
public class ArrayTest{

    public static void main(String args[]) {

        //test our method to see if array contains a certain value or not
        Integer[] input = new Integer[]{1, 2, 3, 4, 5};
        System.out.printf("Does array %s has %s?  %b %n",
                          Arrays.toString(input), 5, isExists(input, 5));
        System.out.printf("Does array %s contains %s?  %b %n", 
                          Arrays.toString(input), 5, contains(input, 5));
        System.out.printf("Does array %s has %s?  %b %n", 
                          Arrays.toString(input), 6, isExists(input, 6));
        System.out.printf("Does Integer array %s contains %s?  %b %n", 
                          Arrays.toString(input), 6, contains(input, 6));

        String[] names = new String[]{"JP", "KP", "RP", "OP", "SP"};
        System.out.printf("Does array %s has %s?  %b %n", 
                          Arrays.toString(names), "JP", isExists(names, "JP"));
        System.out.printf("Does String array %s contains %s?  %b %n", 
                          Arrays.toString(names), "JP", contains(names, "JP"));
        System.out.printf("Does array of names %s has %s?  %b %n",
                          Arrays.toString(names), "MP", isExists(names, "MP"));
        System.out.printf("Does array %s contains %s?  %b %n",
                          Arrays.toString(names), "UP", contains(names, "UP"));

    }

    /**
     * Function to test if Array contains a certain value or not. 
     * This method take advantage of
     * contains() method of ArrayList class, by converting array to ArrayList.
     *
     * @return true if array contains 
     */
    public static <T> boolean isExists(final T[] array, final T object) {
        return Arrays.asList(array).contains(object);
    }


   /**
     * Another method to search an item in Java array. 
     * This method loop through array and use
     * equals() method to search element. This actually performs 
     * a linear search over array in Java
     *
     *@return true if array has provided value.
     */
    public static <T> boolean contains(final T[] array, final T v) {
        for (final T e : array) {
            if (e == v || v != null && v.equals(e)) {
                return true;
            }
        }

        return false;
    }

}

Output:
Does array [1, 2, 3, 4, 5] has 5?  true
Does array [1, 2, 3, 4, 5] contains 5?  true
Does array [1, 2, 3, 4, 5] has 6?  false
Does Integer array [1, 2, 3, 4, 5] contains 6?  false
Does array [JP, KP, RP, OP, SP] has JP?  true
Does String array [JP, KP, RP, OP, SP] contains JP?  true
Does array of names [JP, KP, RP, OP, SP] has MP?  false
Does array [JP, KP, RP, OP, SP] contains UP?  false

You can see the result as true or false if the array contains a particular value or not. Like in the first output array contains 5 so the result is true, but in the third example, the array doesn't contain 6, so the result is false.

How to check if array contains a particular value in Java



That's all on how to find if an array contains a particular value or not. As I told you, if you are allowed to use Java API, then you can either use the binarySearch() method of Java Java .util.Arrays class or you can simply convert your array to ArrayList and then call its contains() method.

If using Java API or any third party is not allowed, then you can write your own function to search an element in an array using either binary search or linear search method. If you write binary search, then be prepared with both iterative and recursive methods, as the Interviewer will more likely to ask both of them.



Other Java Array articles article from Java67 blog
  1. How to remove an element from the array without using a third-party library (check here)
  2. 10 points about array in Java (read here)
  3. 10 Free Courses to learn Data Structure and Algorithms (courses)
  4. Difference between array and ArrayList in Java (see here)
  5. How to loop over an array in Java (read here)
  6. 4 ways to sort array in Java (see here)
  7. 100+ Data Structure and Algorithms Problems (solved)
  8. How to convert Array to String in Java (read here)
  9. How to print array in Java with examples (read here)
  10. 10 Books to learn Data Structure and Algorithms (books)
  11. How to compare two arrays in Java (check here)
  12. How to declare and initialize a multi-dimensional array in Java (see here)
  13. How to find the largest and smallest number in an array in Java (read here)
  14. How to find two maximum number on an integer array in Java (check here)

Thanks for reading this article so far. If you like this article, then please share it with your friends and colleagues. If you have any questions or doubt then, please let us know, and I'll try to find an answer for you. As always suggestions, comments, innovation, and better The answers are most welcome.

P. S. - If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check the Data Structure in Java free course on Udemy. It's completely free, and all you need to do is create a free Udemy account to enroll in this course. 

6 comments:

  1. There are couple of more efficient way to solve this problem
    - sort the array and use binary search
    - use BitSet

    ReplyDelete
  2. Is it not that abrupt 'return' statement is considered harmful?

    ReplyDelete
  3. Replies
    1. Thanks Suchitra, glad you find this website useful.

      Delete
  4. A very easy solution is provided in java 8 using 'Instream',

    int array[]={1,2,3,45,45,7,8,9,5,4,2,0,5};

    System.out.println(IntStream.of(array).anyMatch(x -> x ==4));

    ReplyDelete
  5. package JavaProgramCode;

    import java.util.Scanner;

    public class NumberPresent {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    int num[] = new int[] {2,4,5,6};
    Scanner obj = new Scanner(System.in);
    int temp=0;
    System.out.println("Please enter the number you want to find: ");
    int a = obj.nextInt();
    for(int i=0;i<num.length;i++) {
    temp = num[i];
    if(a==temp) {
    System.out.println("Yes the provided number is present in the array: "+temp);
    break;
    }
    }
    }

    }

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.