Question
I have a String[] array like this:
public static final String[] VALUES = new String[] {"AB", "BC", "CD", "AE"};
Given a String s, what is a good way to test whether VALUES contains s in Java?
Short Answer
By the end of this page, you will understand how to check whether a Java array contains a specific value, why arrays do not have a built-in contains() method, and which approaches are most useful in real code. You will also see when to use a loop, Arrays.asList(...).contains(...), streams, or a Set instead of an array.
Concept
In Java, an array is a fixed-size container that stores multiple values of the same type. A String[] can hold many strings, but arrays themselves do not provide convenience methods like contains().
That means if you want to check whether an array has a particular value, you need to use one of these approaches:
- loop through the array manually
- convert the array to a list and use
contains() - use a stream
- use a different data structure, such as a
Set, if membership checks are common
This matters because checking whether a value exists is a very common task in programming:
- validating user input
- checking whether a code is allowed
- filtering data
- applying conditional logic based on known values
For String values, an important detail is that you should usually compare with .equals() rather than ==.
==checks whether two references point to the same object.equals()checks whether the text content is the same
For example:
String a = new ();
();
System.out.println(a == b);
System.out.println(a.equals(b));
Mental Model
Think of an array like a row of labeled boxes.
If you want to know whether one box contains a certain label, you have to check the boxes one by one unless you first reorganize them into a structure that is better for lookup.
- Array: a row of boxes
- Loop: walking past each box and reading its label
- List contains: borrowing a helper tool that checks the row for you
- Set: turning the values into a membership checklist for faster lookups
For strings, imagine two pieces of paper that both say AB.
==asks: “Are these the exact same piece of paper?”.equals()asks: “Do these papers have the same text written on them?”
Most of the time, for strings, you care about the text, so you use .equals().
Syntax and Examples
1. Manual loop
This is the most direct and beginner-friendly approach.
public static boolean contains(String[] array, String target) {
for (String value : array) {
if (value.equals(target)) {
return true;
}
}
return false;
}
Usage:
String s = "BC";
boolean exists = contains(VALUES, s);
System.out.println(exists); // true
This checks each element until it finds a match.
2. Null-safe manual loop
If target or array elements might be null, use Objects.equals().
import java.util.Objects;
public static boolean contains {
(String value : array) {
(Objects.equals(value, target)) {
;
}
}
;
}
Step by Step Execution
Consider this example:
public static boolean contains(String[] array, String target) {
for (String value : array) {
if (value.equals(target)) {
return true;
}
}
return false;
}
And this input:
String[] values = {"AB", "BC", "CD", "AE"};
String target = "CD";
Step-by-step
- The method starts.
- The loop reads the first element:
value = "AB". - It checks
value.equals(target). - That becomes
"AB".equals("CD"), which isfalse. - The loop continues.
- The next element is
value = "BC". - It checks
"BC".equals("CD"), which isfalse.
Real World Use Cases
Checking whether an array contains a value appears in many common tasks:
Input validation
String[] validRoles = {"ADMIN", "USER", "GUEST"};
String role = "USER";
if (Arrays.asList(validRoles).contains(role)) {
System.out.println("Valid role");
}
Allowed file extensions
String[] allowedExtensions = {"jpg", "png", "gif"};
String extension = "png";
You can check whether an uploaded file type is allowed.
Feature flags or known codes
String[] supportedRegions = {"US", "CA", "UK"};
Before enabling a feature, you can verify whether a region is supported.
Data filtering
When processing records, you may only keep rows whose category is in a known list of allowed values.
API request validation
An API may accept only certain status values such as:
Real Codebase Usage
In real projects, developers often choose the approach based on how often the lookup happens and what kind of data is involved.
Simple one-off checks
A small loop is common when:
- the array is small
- performance is not a concern
- readability matters most
for (String value : VALUES) {
if (value.equals(input)) {
return true;
}
}
return false;
Validation with guard clauses
Developers often reject invalid values early.
if (!Arrays.asList(VALUES).contains(input)) {
throw new IllegalArgumentException("Unsupported value: " + input);
}
This is a guard clause: fail fast if the input is not allowed.
Null-safe validation
import java.util.Objects;
for (String value : VALUES) {
if (Objects.equals(value, input)) {
return true;
}
}
Useful when data may come from databases, APIs, or forms.
Replacing arrays with sets for lookup-heavy code
If the code frequently checks membership, developers often store values in a .
Common Mistakes
Using == instead of .equals()
Broken code:
if (value == target) {
return true;
}
Why it is wrong:
==compares object references- two different
Stringobjects can contain the same text
Correct code:
if (value.equals(target)) {
return true;
}
Causing a NullPointerException
Broken code:
if (value.equals(target)) {
return true;
}
This breaks if value is null.
Safer version:
import java.util.Objects;
if (Objects.equals(value, target)) {
;
}
Comparisons
| Approach | Example | Best for | Notes |
|---|---|---|---|
| Manual loop | for (String v : array) | Learning, simple logic, full control | Easy to understand |
Arrays.asList(...).contains(...) | Arrays.asList(array).contains(x) | Quick readable checks | Convenient for small arrays |
| Stream | Arrays.stream(array).anyMatch(x::equals) | Functional style | Can be less beginner-friendly |
Set.contains(...) | set.contains(x) | Frequent membership checks | Usually the best lookup structure |
Array vs List vs Set
Cheat Sheet
Quick ways to check whether a Java array contains a value
Manual loop
for (String value : VALUES) {
if (value.equals(s)) {
return true;
}
}
return false;
Null-safe loop
import java.util.Objects;
for (String value : VALUES) {
if (Objects.equals(value, s)) {
return true;
}
}
return false;
Using Arrays.asList
import java.util.Arrays;
boolean exists = Arrays.asList(VALUES).contains(s);
Using streams
import java.util.Arrays;
boolean exists = Arrays.stream(VALUES).anyMatch(s::equals);
Best for many lookups
Set<String> values = Set.of(, , , );
values.contains(s);
FAQ
Why does Java array not have a contains() method?
Arrays in Java are basic language-level containers, not full collection objects like List or Set. That is why helper methods or loops are needed.
What is the simplest way to check if a string array contains a value?
For small arrays, Arrays.asList(array).contains(value) is simple and readable.
Should I use == or .equals() to compare strings in Java?
Use .equals() because it compares string content. == only checks whether both references point to the same object.
What if the array or target can contain null?
Use Objects.equals(a, b) because it safely compares values even when one or both are null.
Is Arrays.asList(array).contains(value) slow?
For small arrays and occasional checks, it is fine. If you do many lookups, a Set is usually a better choice.
Is a Set better than an array for checking whether a value exists?
Mini Project
Description
Build a small Java validator that checks whether a country code is allowed. This demonstrates how to test membership in a collection of known values and how to choose between an array and a set for validation logic.
Goal
Create a program that accepts a country code string and reports whether it is in the allowed list.
Requirements
- Define a fixed list of allowed country codes.
- Write a method that checks whether an input code is allowed.
- Handle
nullinput safely. - Test the method with both valid and invalid codes.
Keep learning
Related questions
Avoiding Java Code in JSP with JSP 2: EL and JSTL Explained
Learn how to avoid Java scriptlets in JSP 2 using Expression Language and JSTL, with examples, best practices, and common mistakes.
Choosing a @NotNull Annotation in Java: Validation vs Static Analysis
Learn how Java @NotNull annotations differ, when to use each one, and how to choose between validation, IDE hints, and static analysis tools.
Convert a Java Stack Trace to a String
Learn how to convert a Java exception stack trace to a string using StringWriter and PrintWriter, with examples and common mistakes.