Hello guys, one of the common coding questions from Java interviews ishow 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 thebinarySearch() method of Java Java.util.Arrays class or taking advantage ofArrayList 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 tosearch 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 alittle tricky but not too difficult either, therecursive 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.
If you come up with those solutions, the Interviewer will surely ask you to write down a method tosearch 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 alittle tricky but not too difficult either, therecursive 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.
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.
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 ofhow 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 methodsisExists() andcontains(), which returns true if the value is present in the array. The first method usescontains() method ofArrayList by first converting given anarray 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 likeThe Complete Java Masterclass on Udemy to learn Generics better. It's very important for writing production-quality Java code.
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 aString[]with values like so:publicstaticfinal 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 ofhow 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 methodsisExists() andcontains(), which returns true if the value is present in the array. The first method usescontains() method ofArrayList by first converting given anarray 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 likeThe Complete Java Masterclass on Udemy to learn Generics better. It's very important for writing production-quality Java code.
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.importjava.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*/publicclassArrayTest{publicstaticvoidmain(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 */publicstatic <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. */publicstatic <T>boolean contains(final T[] array,final T v) {for (final T e : array) {if (e == v || v !=null && v.equals(e)) {returntrue; } }returnfalse; }}Output:Does array [1,2,3,4,5] has5?trueDoes array [1,2,3,4,5] contains5?trueDoes array [1,2,3,4,5] has6?falseDoes Integer array [1,2,3,4,5] contains6?falseDoes array [JP, KP, RP, OP, SP] has JP?trueDoes String array [JP, KP, RP, OP, SP] contains JP?trueDoes array of names [JP, KP, RP, OP, SP] has MP?falseDoes array [JP, KP, RP, OP, SP] contains UP?false
You can see the result astrue orfalseif 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.
That's all onhow 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 itscontains() 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.
OtherJava Array articles article from Java67 blog
- How to remove an element from the array without using a third-party library (check here)
- 10 points about array in Java (read here)
- 10 Free Courses to learn Data Structure and Algorithms (courses)
- Difference between array and ArrayList in Java (see here)
- How to loop over an array in Java (read here)
- 4 ways to sort array in Java (see here)
- 100+ Data Structure and Algorithms Problems (solved)
- How to convert Array to String in Java (read here)
- How to print array in Java with examples (read here)
- 10 Books to learn Data Structure and Algorithms (books)
- How to compare two arrays in Java (check here)
- How to declare and initialize a multi-dimensional array in Java (see here)
- How to find the largest and smallest number in an array in Java (read here)
- 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 theData 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.
There are couple of more efficient way to solve this problem
ReplyDelete- sort the array and use binary search
- use BitSet
Is it not that abrupt 'return' statement is considered harmful?
ReplyDeletegood website
ReplyDeleteThanks Suchitra, glad you find this website useful.
DeleteA very easy solution is provided in java 8 using 'Instream',
ReplyDeleteint array[]={1,2,3,45,45,7,8,9,5,4,2,0,5};
System.out.println(IntStream.of(array).anyMatch(x -> x ==4));
package JavaProgramCode;
ReplyDeleteimport 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;
}
}
}
}