java

How to check if an element exists in an array in Java

In this tutorial, we are going to see how to check if an element exists or not in an array of String using the list.contains() method or Int in Java.
 

Check if an element exists in an array of String :
import java.util.*;

public class Main {

    public static void main(String[] args) {

        String[] arr = {"Java", "PHP", "C++"};

        // Convert the array to list
        List<string> list = Arrays.asList(arr);
        
        if(list.contains("Java")){
            System.out.println("The element exists");
        }
    }
}

Output:

The element exists

 
[st_adsense]  

Check if an element exists in an array of Int :
public class Main {

    public static boolean check(int[] arr, int val) {
        boolean b = false;
		
        for(int i : arr){
            if(i == val){
                b = true;
                break;
            }
        }
        return b;
    }

    public static void main(String[] args) {
        int[] arr = {9, 0, 8, 2, 5, 7, 3};
        if(check(arr, 5)){
            System.out.println("5 exists in the array.");
        }
    }
}

Output:

5 exists in the array.
[st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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