Write a Java Program to Check if An Array Contains a Given Value

Java Program to Check if An Array Contains a Given Value

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Check if An Array Contains a Given Value
Java Program to Check if An Array Contains a Given Value

Write a Java Program to Check if An Array Contains a Given Value

PROGRAM: Java Program to Check if An Array Contains a Given Value

/*Java Program to Check if An Array Contains a Given Value*/

1: Check if Int Array contains a given value

class Main {
  public static void main(String[] args) {

    int[] num = {1, 2, 3, 4, 5};
    int toFind = 3;
    boolean found = false;

    for (int n : num) {
      if (n == toFind) {
        found = true;
        break;
      }
    }
    
    if(found)
      System.out.println(toFind + " is found.");
    else
      System.out.println(toFind + " is not found.");
  }
}

2: Check if an array contains the given value using Stream

import java.util.stream.IntStream;

class Main {
public static void main(String[] args) {

int[] num = {1, 2, 3, 4, 5};
int toFind = 7;

boolean found = IntStream.of(num).anyMatch(n -> n == toFind);

if(found)
System.out.println(toFind + ” is found.”);
else
System.out.println(toFind + ” is not found.”);

}
}


3: Check if an array contains a given value for non-primitive types

import java.util.Arrays;

class Main {
  public static void main(String[] args){

    String[] strings = {"One","Two","Three","Four","Five"};
    String toFind= "Four";

    boolean found = Arrays.stream(strings).anyMatch(t -> t.equals(toFind));

    if(found)
      System.out.println(toFind + " is found.");
    else
      System.out.println(toFind + " is not found.");
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *