Java - Check if array contains the value


Example 1: Array of Strings
public class Example {

    public static void main(String... args) {

        String[] myArray = new String[6];

        myArray[0] = "USA";
        myArray[1] = "France";
        myArray[2] = "Germany";
        myArray[3] = "Australia";
        myArray[4] = "Japan";
        myArray[5] = "India";

        System.out.println(checkArrayForElement(myArray,"Japan"));
        System.out.println(checkArrayForElement(myArray,"China"));

    }

    public static boolean checkArrayForElement(String[] myArray, String country) {

        for (int i = 0; i < myArray.length; i++) {

            if(myArray[i].equals(country)) {
                return true;
            }
        }

        return false;
    }
}
Output:

true
false

Example 2: Array of Integers using foreach loop
public class Example {

    public static void main(String... args) {

        int[] myIntArray = {1, 4, 0, 11, 22, 34, 24, 12};
        System.out.println(checkArrayForElement(myIntArray,12));
        System.out.println(checkArrayForElement(myIntArray,10));
    }
    
    public static boolean checkArrayForElement(int myIntArray, int inNo) {

        for (int no: myIntArray) {
            if(no == inNo) {
                return true;
            }
        }
        return false;
    }
}
Output:

true
false

In Example 1, we have an array of Strings and we iterate over the array's length and check with an if the condition that the array contains an element or not using equals() methods. In Example 2 we are making use of for each loop to do the same with an array of integers.




Recent Posts:




Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.