Report this

What is the reason for this report?

How to Check if a Java Array Contains a Value?

Updated on September 16, 2025
How to Check if a Java Array Contains a Value?

Introduction

Checking if a Java array contains a specific value is one of the most common operations you’ll perform as a Java developer. Whether you’re validating user input, processing data, or implementing search functionality, you need a reliable way to find elements in arrays.

Java offers multiple approaches to solve this problem, each optimized for different scenarios. The method you choose can significantly impact your application’s performance, especially when dealing with large datasets or frequent lookups.

This comprehensive guide covers the four essential methods every Java developer should know: the enhanced for-loop that works in any situation, the convenient Arrays.asList().contains() method for quick lookups in object arrays, modern Java 8 Streams with their functional programming power, and the lightning-fast binary search for sorted arrays. You’ll discover how to handle both primitive arrays like int[] and object arrays like String[], avoid common pitfalls that can break your code, and understand the performance implications of each approach.

By the end of this guide, you’ll know exactly which method to use in any situation and how to implement it correctly for maximum performance and reliability.

Key Takeaways:

  • A for-loop is the most fundamental and universally compatible way to search any type of Java array, including primitives and objects.
  • Java 8+ Streams with anyMatch() provide a modern, readable, and functional approach to array searching that is ideal for clean, expressive code.
  • The Arrays.asList().contains() method is a convenient one-liner for object arrays only. It does not work correctly with primitive arrays like int[].
  • For maximum performance on large arrays, use Arrays.binarySearch(), but be sure the array is sorted first.
  • Use == for comparing primitives and .equals() for comparing objects to ensure correct value equality.
  • To check if an array contains multiple values, convert both arrays to Lists and use the containsAll() method.
  • Streams are ideal for finding an object in an array based on a specific property, such as an ID or name, using anyMatch() with a lambda expression.

What is the For-Loop method (The Universal Approach)?

The for-loop is the easiest and most universal way to check for an element in an array. It’s a classic for a reason: it’s built into the core of Java, requires no special libraries, and works reliably for every type of array. The strategy is simple: iterate through each element and check for a match.

For efficiency, it’s a best practice to use the break keyword to exit the loop as soon as you find your value. This approach has O(n) time complexity in the worst case, but O(1) best case when the element is found immediately.

What is Searching in an Object Array (e.g., String[])?

When working with object arrays like String[], Integer[], or custom objects, you must use the .equals() method for comparison. This checks if the objects are meaningfully equivalent, not just if they are the same object in memory.

public class FindInObjectArray {
    public static void main(String[] args) {
        String[] tools = {"Hammer", "Screwdriver", "Wrench"};
        String toolToFind = "Wrench";
        boolean isFound = false;

        for (String tool : tools) {
            if (tool.equals(toolToFind)) {
                isFound = true;
                break; 
            }
        }

        System.out.println("Found '" + toolToFind + "': " + isFound); 
    }
}

Output:

Found 'Wrench': true

What is Searching in a Primitive Array (e.g., int[])?

For primitive arrays like int[], double[], or char[], you use the == operator. This operator directly compares the values of the primitive types.

public class FindInPrimitiveArray {
    public static void main(String[] args) {
        int[] grades = {88, 92, 77, 100, 85};
        int gradeToFind = 77;
        boolean isFound = false;

        for (int grade : grades) {
            // Use == for primitives
            if (grade == gradeToFind) {
                isFound = true;
                break;
            }
        }

        System.out.println("Found grade '" + gradeToFind + "': " + isFound); 
    }
}

Output:

Found grade '77': true

What is Null-Safe Implementation for Object Arrays

Real-world applications often deal with arrays that might contain null values. Here’s how to handle them safely:

import java.util.Objects;

public class NullSafeArraySearch {
    public static boolean containsValue(String[] array, String value) {
        if (array == null) return false;
        
        for (String element : array) {
            if (Objects.equals(element, value)) {
                return true;
            }
        }
        return false;
    }
    
    public static void main(String[] args) {
        String[] colors = {"red", null, "blue", "green"};
        boolean hasNull = containsValue(colors, null);    
        boolean hasBlue = containsValue(colors, "blue");  
        boolean hasYellow = containsValue(colors, "yellow"); 
        
        System.out.println("Contains null: " + hasNull);
        System.out.println("Contains blue: " + hasBlue);
        System.out.println("Contains yellow: " + hasYellow);
    }
}

Output:

Contains null: true
Contains blue: true
Contains yellow: false

Objects.equals() prevents a NullPointerException and correctly handles cases where either the array element or the search value is null.

The for-loop method is ideal when you need maximum compatibility, are working with small to medium-sized arrays, or want the most readable and maintainable code. It’s also the fastest approach for unsorted arrays and doesn’t require any additional memory allocation.

What is Java 8 Streams anyMatch()? (The Modern Approach)

Since Java 8, Streams offer a highly readable, functional way to work with collections of data, including arrays. The anyMatch() method is perfect for our task. It checks if any element in the stream matches a given condition and returns true as soon as it finds one, making it very efficient with short-circuit evaluation.

Example with an Object Array

For object arrays, you create a stream using Arrays.stream(). You then provide a lambda expression to anyMatch() to define your search condition.

import java.util.Arrays;

public class StreamObjectSearch {
    public static void main(String[] args) {
        String[] languages = {"Java", "Python", "JavaScript", "Go"};
        String langToFind = "JavaScript";

        boolean isFound = Arrays.stream(languages)
                                .anyMatch(s -> s.equals(langToFind));
        
        boolean isFoundRef = Arrays.stream(languages)
                                  .anyMatch(langToFind::equals);

        System.out.println("Found '" + langToFind + "': " + isFound); 

    }
}

Output:

Found 'JavaScript': true

Example with a Primitive Array (IntStream, etc.)

Java provides specialized streams for primitives (like IntStream, DoubleStream, LongStream) that are more memory and performance-efficient than using a generic Stream<Integer>. You can create them using Arrays.stream() or IntStream.of().

import java.util.Arrays;

public class StreamPrimitiveSearch {
    public static void main(String[] args) {
        int[] sensorReadings = {25, 31, 28, 45, 33};
        int readingToFind = 45;

        boolean isFound = Arrays.stream(sensorReadings)
                                .anyMatch(reading -> reading == readingToFind);
        
        System.out.println("Found reading '" + readingToFind + "': " + isFound); 

    }
}

Output:

Found reading '45': true

Streams are ideal when you prefer a functional programming style, are already working with Stream pipelines, or want highly readable code. However, they have slight overhead compared to simple for-loops for small arrays.

What is the Arrays.asList().contains() method (For Object Arrays Only)?

This method is a popular and convenient one-liner for checking for an element, but it has a significant limitation: it only works correctly with object arrays.

What is Correct Usage with Object Arrays

You can quickly convert an object array into a List view using Arrays.asList() and then call the list’s contains() method.

import java.util.Arrays;

public class AsListObjectSearch {
    public static void main(String[] args) {
        String[] fruits = {"Apple", "Banana", "Orange"};
        
        boolean hasBanana = Arrays.asList(fruits).contains("Banana");
        
        System.out.println("Array has 'Banana': " + hasBanana); 

    }
}

Output:

Array has 'Banana': true

Why Arrays.asList() Fails for Primitive Arrays

This is a common trap for Java developers. If you use Arrays.asList() on a primitive array like int[], it will not work as expected. If you see only one element in the resulting list with class [I, that means the primitive array was treated as a single object.

The reason is that Arrays.asList(new int[]{...}) does not create a List<Integer>. Instead, it creates a List<int[]>, a list that contains a single element, which is the entire array itself. When you call .contains(20), you’re asking if the list contains the integer 20, but the list only contains an int[] object, so the answer is always false.

Important Note: This code demonstrates the wrong way to do it.

import java.util.Arrays;

public class AsListPrimitivePitfall {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30};
        
        boolean found = Arrays.asList(numbers).contains(20);
        
        System.out.println("Found 20: " + found);
        
        System.out.println("List size: " + Arrays.asList(numbers).size()); // Output: 1
        System.out.println("List contains: " + Arrays.asList(numbers).get(0).getClass()); 
    }
}

Output:

Found 20: false
List size: 1
List contains: class [I

The bottom line is, always use a for-loop or a Stream for primitive arrays.

What is the Arrays.binarySearch() method (The Fastest Method for Sorted Arrays)?

If performance is critical and you’re working with large arrays, binarySearch() is by far the fastest option with O(log n) time complexity. However, it comes with one absolute requirement.

The binarySearch() algorithm only works on sorted data. It works by repeatedly dividing the search interval in half. If the array is not sorted first, the results will be incorrect and unpredictable. You can sort an array using Arrays.sort().

The binarySearch() method’s return value tells you both if the element was found and where it is (or would be):

  • If found: Returns the index of the element (0 or greater)
  • If not found: Returns a negative number representing -(insertion point) - 1
import java.util.Arrays;

public class BinarySearchExample {
    public static void main(String[] args) {
        String[] vowels = {"U", "A", "E", "I", "O"}; 
        
        Arrays.sort(vowels);
        System.out.println("Sorted array: " + Arrays.toString(vowels));

        int indexFound = Arrays.binarySearch(vowels, "I");
        
        int indexNotFound = Arrays.binarySearch(vowels, "F");

        System.out.println("'I' is at index: " + indexFound);
        System.out.println("'F' would be at index: " + indexNotFound);
        
        if (indexFound >= 0) {
            System.out.println("'I' was found!");
        }
        
        if (indexNotFound < 0) {
            System.out.println("'F' was not found!");
            int insertionPoint = -(indexNotFound + 1);
            System.out.println("'F' would be inserted at index: " + insertionPoint);
        }
    }
}

Output:

Sorted array: [A, E, I, O, U]
'I' is at index: 2
'F' would be at index: -3
'I' was found!
'F' was not found!
'F' would be inserted at index: 2

Binary search is ideal when you have large sorted arrays (1000+ elements), need maximum performance, or are performing many searches on the same array. For small arrays or one-time searches, the overhead of sorting may not be worth it.

What is the containsAll method?

Sometimes you may need to check if an array contains not just one value, but a whole collection of them. For example, you might want to verify if a user has all the required permissions from a list, or check if a shopping cart contains all items from a promotion bundle.

While you could write complex nested loops to solve this, there’s a much cleaner and more readable way using Java’s Collections framework. The strategy is to convert your arrays into Lists and then use the List.containsAll() method.

This method returns true only if the source list contains all of the elements from the target list.

import java.util.Arrays;
import java.util.List;

public class ContainsAllExample {
    public static void main(String[] args) {
        String[] userPermissions = {"READ", "WRITE", "EXECUTE", "DELETE"};
        String[] requiredPermissions = {"WRITE", "READ"};

        List<String> userPermsList = Arrays.asList(userPermissions);
        List<String> requiredPermsList = Arrays.asList(requiredPermissions);

        boolean hasAllRequired = userPermsList.containsAll(requiredPermsList);

        System.out.println("User has all required permissions: " + hasAllRequired); 

        String[] minimumPermissions = {"READ", "COMMENT"};
        boolean hasMinimum = userPermsList.containsAll(Arrays.asList(minimumPermissions));
        System.out.println("User has minimum permissions: " + hasMinimum);
    }
}

Output:

User has all required permissions: true
User has minimum permissions: false

This Arrays.asList() approach works best for object arrays like String[], Integer[], etc. For primitive arrays (int[], double[]), you’ll need to convert them using Streams first with .boxed() and Collectors.toList().

For large arrays or frequent checks, consider converting the source array to a HashSet first for better performance; this changes the time complexity from O(n*m) to O(n+m). The containsAll() method uses the .equals() method for comparison, so it handles null values safely.

Comparing Array Search Techniques

Here is a summary table comparing the key characteristics of each technique we discussed. This provides a quick reference to help you choose the best method for your specific situation.

Method Works With Best For Performance Key Requirement / Caveat
Stream anyMatch() Primitives & Objects Modern, readable code; functional programming style. O(n) Slight overhead on very small arrays, but highly expressive.
For-Loop Primitives & Objects Universal solution; small arrays; maximum compatibility. O(n) Verbose; requires manual use of == for primitives and .equals() for objects.
Arrays.asList().contains() Objects Only A quick, convenient one-liner for object arrays. O(n) Fails silently for primitive arrays (like int[], double[]).
Arrays.binarySearch() Primitives & Objects Maximum performance on large, sorted arrays. O(log n) The array must be sorted first for correct results.

Performance Analysis (Big O Notation)

Before diving into the code, it’s crucial to understand how each method performs, especially as the size of your data grows. Time complexity, often expressed using Big O notation, gives us a standardized way to measure this. It describes the worst-case scenario for how the execution time of an algorithm scales with the input size (n).

Method Time Complexity Notes
Linear Scan (for-loop, Streams) O(n) Execution time grows linearly with the number of elements. In the worst case, it must check every element.
Arrays.asList().contains() O(n) This method also performs a linear search under the hood.
Arrays.binarySearch() O(log n) Exceptionally fast for large arrays. However, it requires a one-time sorting cost of O(n log n).
HashSet.contains() O(1) Offers the fastest lookup time (constant on average). It requires an initial conversion cost of O(n) to build the set.

Let’s break down these complexities.

Linear Scan: O(n)

Methods like a for-loop, Java Streams, or Arrays.asList().contains() perform a linear scan. This means they start at the first element and check each one sequentially until they find a match or reach the end of the array. If your array has 1,000 elements, it might take 1,000 checks in the worst case. If it has 1,000,000 elements, it could take 1,000,000 checks. The time taken grows in direct proportion to the array size.

Binary Search: O(log n)

A binary search is significantly more efficient but comes with a major prerequisite: the array must be sorted. The algorithm works by repeatedly dividing the search interval in half. It compares the target value to the middle element. If they don’t match, the half in which the target cannot lie is eliminated, and the search continues on the remaining half.

This “divide and conquer” strategy makes it incredibly fast. For an array of 1,000,000 elements, a binary search takes at most 20 comparisons (2**20; approx 1,000,000), a massive improvement over the potential million comparisons of a linear scan. The main trade-off is the initial sorting cost, which has a time complexity of O(n log n). This approach is ideal when you need to perform many searches on an array that is already sorted or can be sorted once and reused.

Using Sets for Faster Lookups: O(1)

For scenarios involving multiple lookups on the same array, converting it to a HashSet is the most performant strategy. A HashSet uses a hash code to store elements, allowing it to check for the presence of an element in average constant time, or O(1). This means that regardless of whether the set has 100 elements or 100 million, the time to find an element remains roughly the same.

The process involves two steps:

  1. Conversion: Create a HashSet from the array. This is a one-time operation with a time complexity of $O(n), as each element from the array must be inserted into the set.
  2. Lookup: Use the HashSet.contains() method for each check. This step is extremely fast at $O(1).

This approach is the clear winner when the cost of the initial conversion is offset by the speed of a large number of subsequent lookups.

Building a Reusable Solution with Generics

In many use cases, our methods are tied to a specific data type like String or int. A more robust and reusable solution would work with any object type. This is where generics come in. By creating a generic method, you can write the logic once and apply it to arrays of String, Integer, Customer, or any other object.

Here’s how to write a generic contains() method that works for any object array.

import java.util.Objects;

public class ArrayUtils {

    public static <T> boolean contains(T[] array, T value) {
        // Return false immediately if the array is null or empty.
        if (array == null || array.length == 0) {
            return false;
        }

        for (T element : array) {
            // Use Objects.equals() for null-safe comparison.
            // This correctly handles cases where 'element' or 'value' is null.
            if (Objects.equals(element, value)) {
                return true;
            }
        }
        
        return false;
    }

    public static void main(String[] args) {
        String[] fruits = {"Apple", "Banana", "Orange"};
        System.out.println("Contains 'Banana'? " + contains(fruits, "Banana")); // true
        System.out.println("Contains 'Grape'? " + contains(fruits, "Grape"));   // false

        Integer[] numbers = {1, 2, 3, 4, 5};
        System.out.println("Contains 3? " + contains(numbers, 3));       // true
        System.out.println("Contains 10? " + contains(numbers, 10));     // false

        String[] nullableArray = {"A", null, "B"};
        System.out.println("Contains null? " + contains(nullableArray, null)); // true
    }
}

Key points of this generic method:

  • Type Parameter <T>: Declares that the method operates on a generic type T.
  • Parameters T[] array and T value: The method accepts an array of type T and a value of type T.
  • Objects.equals(element, value): This is a crucial detail. Using the == operator compares object references, which is not what we want. The element.equals(value) method would throw a NullPointerException if element were null. Objects.equals() handles null values gracefully and provides the correct logical comparison.

Note: Generics in Java do not work with primitive types (int, double, etc.). To use this method with primitives, you must use their corresponding wrapper classes (Integer, Double, etc.).

Leveraging Third-Party Libraries

While it’s good to know how to implement these checks yourself, you don’t always have to reinvent the wheel. The Java ecosystem is rich with libraries that provide robust, well-tested utility functions. One of the most popular is Apache Commons Lang.

Its ArrayUtils class offers a convenient contains() method that simplifies the entire process. It’s null-safe and has overloaded versions for both primitive and object arrays.

First, add the Apache Commons Lang dependency to your project. If you’re using Maven, add this to your pom.xml:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version>
</dependency>

Then, you can use it directly in your code:

import org.apache.commons.lang3.ArrayUtils;

public class CommonsLangExample {
    public static void main(String[] args) {
        // Example with an object array
        String[] colors = {"Red", "Green", "Blue"};
        boolean hasGreen = ArrayUtils.contains(colors, "Green"); // true
        System.out.println("Array contains 'Green': " + hasGreen);

        // Example with a primitive array
        int[] numbers = {10, 20, 30, 40, 50};
        boolean hasThirty = ArrayUtils.contains(numbers, 30); // true
        System.out.println("Array contains 30: " + hasThirty);

        // It handles null arrays safely without throwing an exception
        int[] nullArray = null;
        boolean inNull = ArrayUtils.contains(nullArray, 5); // false
        System.out.println("Search in null array: " + inNull);
    }
}

Using a library like Apache Commons Lang is often a good practice in enterprise projects. It reduces boilerplate code, improves readability, and relies on a thoroughly tested implementation.

How AI Can Help Optimize Array Search in Java

Modern development is no longer a solitary activity; it’s a partnership between the developer and intelligent tools. AI-powered code assistants, integrated directly into IDEs, are fundamentally changing how we write, debug, and optimize code. When it comes to a foundational task like searching an array, these tools can provide significant value beyond simple autocompletion.

Here’s a deeper look at how AI can help you write more efficient and robust array search code.

Context-Aware Algorithm Suggestion

An AI assistant’s primary strength is its ability to understand the broader context of your code. It doesn’t just see a single line; it analyzes the surrounding logic, variable states, and method signatures to offer intelligent recommendations.

For instance, consider a scenario where a developer writes a linear search to find an ID in an array that has just been sorted.

Developer’s Initial Code:

public boolean productIdExists(int[] productIds, int targetId) {
    // Assume productIds array is sorted before this method is called.
    for (int id : productIds) {
        if (id == targetId) {
            return true;
        }
    }
    return false;
}

An advanced AI tool like GitHub Copilot or Gemini would recognize two key pieces of context:

  1. The operation is a search on an array.
  2. A comment, a method parameter name like sortedProductIds, or a preceding call to Arrays.sort() indicates the array is sorted.

Based on this, it would flag the linear search as suboptimal and suggest a more efficient alternative.

AI-Powered Suggestion:

/*
 * AI Suggestion: For a sorted array, Arrays.binarySearch() is more
 * efficient (O(log n)) than a linear scan (O(n)).
 */
public boolean productIdExists(int[] productIds, int targetId) {
    // The productIds array MUST be sorted for this to work correctly.
    return Arrays.binarySearch(productIds, targetId) >= 0;
}

This proactive guidance helps developers, especially those new to performance optimization, leverage the best tool for the job without having to recall the specific time complexities of every algorithm.

AI-Generated Benchmarks

Developers often rely on intuition to gauge performance, but assumptions can be misleading. Is a Java Stream really slower than a for loop for your specific dataset? By how much? Answering these questions requires benchmarking.

Writing proper benchmark code using frameworks like the Java Microbenchmark Harness (JMH) can be complex and time-consuming. This is where you can leverage LLMs to do the heavy lifting.

You can provide a prompt like:

> "Generate a JMH benchmark in Java to compare the performance of a for-loop linear search, a Stream.anyMatch() search, and Arrays.binarySearch() on a sorted integer array with 10 million elements. Test for a case where the target element is near the end of the array."

The AI can then generate the complete, runnable JMH class, saving you hours of setup. This allows you to move from “I think this is faster” to “I have proven this is faster,” enabling data-driven optimization decisions.

Advanced Static Analysis and Bug Prevention

AI assistants act as an intelligent layer on top of traditional linters and static analysis tools. They can identify subtle, logic-based bugs that a standard compiler might miss.

Example 1: Misuse of Arrays.asList()

A classic Java pitfall is using Arrays.asList() with a primitive array.

// Incorrect code
int[] numbers = {10, 20, 30, 40};
List<int[]> list = Arrays.asList(numbers); // Creates a List<int[]> with one element

// This will always be false!
boolean found = list.contains(30);

A standard linter might not flag this, as the code is syntactically valid. However, an AI assistant understands the developer’s intent was likely to create a List<Integer>. It can detect this logical error and warn the developer, suggesting the correct stream-based approach: Arrays.stream(numbers).boxed().collect(Collectors.toList()).

Example 2: Applying Binary Search on Unsorted Data

What happens if you call Arrays.binarySearch() on an array you think is sorted, but isn’t? The result is unpredictable. It might return a valid-looking index or a negative number, but it will be incorrect. An AI tool can trace the lifecycle of the array variable within the method’s scope. If it cannot find a call to Arrays.sort() or another indication of sorting, it can issue a warning:

Warning: Calling Arrays.binarySearch() on 'data' which may not be sorted. This can lead to unpredictable results. Ensure the array is sorted before performing a binary search.

Generating Complex Logic for Real-World Scenarios

Real-world searching is often more complex than finding an integer in an array. You might need to search an array of custom objects based on a specific field.

Consider a Product class:

class Product {
    String productId;
    String name;
    double price;
    // Constructor, getters...
}

Now, imagine you have an array Product[] inventory sorted by productId. To search this using Arrays.binarySearch(), you need to provide a custom Comparator. An AI assistant can generate this entire block of code for you instantly.

AI-Generated Code:

Product[] inventory = getSortedInventory();
String targetId = "PROD-12345";

// Create a key object for the search
Product searchKey = new Product();
searchKey.setProductId(targetId);

// AI can generate this comparator or the entire lambda function
Comparator<Product> idComparator = Comparator.comparing(Product::getProductId);

int index = Arrays.binarySearch(inventory, searchKey, idComparator);

if (index >= 0) {
    System.out.println("Product found: " + inventory[index].getName());
}

By handling this boilerplate, the AI frees up the developer to focus on the higher-level business logic.

Frequently Asked Questions (FAQs)

1. How do I check for a String in an array, ignoring case?

Use a Stream with the equalsIgnoreCase() method for a clean, one-line solution:

String[] colors = {"Red", "green", "BLUE"};
String colorToFind = "Green";

boolean found = Arrays.stream(colors)
                      .anyMatch(c -> c.equalsIgnoreCase(colorToFind)); 

2. Which is faster: a for-loop or a Java 8 Stream?

For-loops are marginally faster on small arrays due to less overhead. However, the performance difference is usually negligible in real-world applications.

Streams are preferred in modern Java development for their readability and expressive power. Unless you’re working with very large arrays or running the check millions of times, prioritize code clarity over micro-optimizations.

3. Why does Arrays.asList(myIntArray).contains(someInt) return false?

This is a common Java pitfall. When you call Arrays.asList() on a primitive array like int[], it doesn’t create a List<Integer>. Instead, it creates a List<int[]> containing the entire array as a single element.

Since the list contains an array object (not individual integers), contains() will always return false when checking for integer values.

For primitive arrays, use a for-loop or a dedicated Stream like IntStream.

4. How do I find an object in an array based on one of its properties?

Use Streams with anyMatch() and a lambda expression that checks the specific field:

Product[] products = { new Product("A-101"), new Product("B-202") };
String idToFind = "B-202";

boolean productExists = Arrays.stream(products)
                              .anyMatch(p -> p.getId().equals(idToFind)); 

5. How do I check if an array contains a null value?

Check for null directly using ==. Calling .equals() on a null element in the array (null.equals(...)) will throw a NullPointerException:

String[] data = {"A", null, "B"};

boolean hasNull = Arrays.stream(data).anyMatch(s -> s == null); 

6. How do I find all indices of a value, not just check if it exists?

Use a traditional for-loop with an index variable, as for-each loops don’t provide index information:

int[] numbers = {10, 20, 30, 20, 50};
int valueToFind = 20;
List<Integer> indices = new ArrayList<>();

for (int i = 0; i < numbers.length; i++) {
    if (numbers[i] == valueToFind) {
        indices.add(i);
    }
}

7. Why does binarySearch() require a sorted array?

Binary search uses a “divide and conquer” strategy, similar to looking up a word in a dictionary. It checks the middle element and eliminates half of the remaining elements based on whether the target value is greater or less than the middle value.

This elimination process only works when elements are in a predictable, sorted order. With an unsorted array, there’s no way to know which half to eliminate, making the search unreliable.

Conclusion

Java offers multiple ways to check if an array contains a specific value—each suited to different scenarios.

The for-loop is the most universally compatible method and works with all types of arrays, including primitives. Java 8+ Streams bring modern, functional syntax that improves readability and integrates well with other Stream operations. The Arrays.asList().contains() method provides a quick one-liner for object arrays, while Arrays.binarySearch() delivers high performance for sorted arrays with large datasets.

Each method has its strengths and trade-offs. By understanding the distinctions—especially between primitive arrays (int[], double[]) and object arrays (String[], Integer[])—you can choose the approach that best fits your use case in terms of performance, clarity, and maintainability.

Use the right tool for the job, and your Java code will be both robust and readable.

Check out these helpful tutorials to continue your learning journey and expand your Java array skills:

Here are some helpful tutorials to deepen your understanding of Java arrays:

  • Java String Array: Learn how to declare, initialize, and work with arrays of strings in Java, including common operations and best practices.
  • Java String Array to String: Discover various ways to convert a string array into a single string, covering methods like String.join(), Arrays.toString(), and manual concatenation.
  • How to Remove Array Elements in Java: Explore techniques for removing elements from arrays in Java, including using lists, streams, and utility methods to handle both primitive and object arrays.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Pankaj Kumar
Pankaj Kumar
Author
See author profile

Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev

Manikandan Kurup
Manikandan Kurup
Editor
Senior Technical Content Engineer I
See author profile

With over 6 years of experience in tech publishing, Mani has edited and published more than 75 books covering a wide range of data science topics. Known for his strong attention to detail and technical knowledge, Mani specializes in creating clear, concise, and easy-to-understand content tailored for developers.

Category:
Tags:

Still looking for an answer?

Was this helpful?

What is the array is of integers?

- abc xyz

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.