How to Check If Array Contains a Value in Java


In this example, we will learn how to check if an Array (String or Primitive type) contains a certain values.

Source Code

package com.beginner.examples;

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

public class CheckStringArray {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String[] strs = new String[] { "Hello", "Hi", "Ok", "Yes" };
		List list = Arrays.asList(strs);
		if (list.contains("Ok")) {
			System.out.println("The string "Ok" exists");
		} else {
			System.out.println("No "Ok" found!");
		}
	}
}

Output:

The string "Ok" exists

Tips

To check if a primitive array contains multiple values, convert the array into a List and compare it like example above.

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments