w3resource logo


Java Programming Exercies

Java Array Exercises: Test if an array contains a specific value

Secondary Nav

Java Array: Exercise-5 with Solution

Write a Java program to test if an array contains a specific value.

Java Code:

public class Exercise5 {
  public static boolean contains(int[] arr, int item) {
      for (int n : arr) {
         if (item == n) {
            return true;
         }
      }
      return false;
   }
   public static void main(String[] args) {
          int[] my_array1 = {
            1789, 2035, 1899, 1456, 2013, 
            1458, 2458, 1254, 1472, 2365, 
            1456, 2265, 1457, 2456};
      System.out.println(contains(my_array1, 2013));
      System.out.println(contains(my_array1, 2015));
   }
}

Java Practice online :

public class Exercise5 {
  public static boolean contains(int[] arr, int item) {
      for (int n : arr) {
         if (item == n) {
            return true;
         }
      }
      return false;
   }
   public static void main(String[] args) {
          int[] my_array1 = {
            1789, 2035, 1899, 1456, 2013, 
            1458, 2458, 1254, 1472, 2365, 
            1456, 2265, 1457, 2456};
      System.out.println(contains(my_array1, 2013));
      System.out.println(contains(my_array1, 2015));
   }
}

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program