Category : Java | Sub Category : Java Programs | By Prasad Bonam Last updated: 2023-08-14 12:51:35 Viewed : 545
To check if an array contains a specific number in Java, you can loop through the array and compare each element with the target number. Here is how you can do it, along with example outputs:
1. Using a Loop:
javapublic class ArrayContainsNumber {
public static void main(String[] args) {
int[] array = {5, 8, 10, 12, 15};
int targetNumber = 10;
boolean contains = containsNumber(array, targetNumber);
if (contains) {
System.out.println("Array contains the number " + targetNumber);
} else {
System.out.println("Array does not contain the number " + targetNumber);
}
}
public static boolean containsNumber(int[] arr, int target) {
for (int num : arr) {
if (num == target) {
return true;
}
}
return false;
}
}
Output:
sqlArray contains the number 10
2. Using Arrays.asList()
and contains()
(for Integer arrays):
Note that this approach only works for arrays of object types, like Integer, not for primitive data types like int.
javaimport java.util.Arrays;
public class ArrayContainsNumber {
public static void main(String[] args) {
Integer[] array = {5, 8, 10, 12, 15};
Integer targetNumber = 10;
boolean contains = Arrays.asList(array).contains(targetNumber);
if (contains) {
System.out.println("Array contains the number " + targetNumber);
} else {
System.out.println("Array does not contain the number " + targetNumber);
}
}
}
Output:
sqlArray contains the number 10
Please note that the first approach using a loop is applicable to both primitive data type arrays (int[]
) and arrays of object types (Integer[]
). The second approach using Arrays.asList()
is specific to arrays of object types.