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.


Top Hashtags:

Advertisements

Advertisements




Advertisements