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
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.
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!