OneCompiler

[Java] How to check if the variable is an array?

How to check if a given variable is an array in Java?

1 Answer

4 years ago by

We can use .getClass().isArray() to check the variable is Array or not.

public class JavaArrays {
	public static void main(String[] args) {
		String[] colors = { "blue", "red", "green", "yellow", "blue" };
		String foo = "bar";
		
		System.out.println(colors.getClass().isArray());
		System.out.println(foo.getClass().isArray());
	}
}

Output:

true
false

Try this code online here: https://onecompiler.com/java/3xmtfx6bn

4 years ago by Karthik Divi