How to check if an object is an array in Java
Overview
This shot discusses how to determine if the object is an array in Java.
Class class in Java
Java has a class named Class in java.lang package. This class is used for reflection purpose.
Every object in Java belongs to a class. The metadata about the class is captured in the Class object. The metadata can be the class’s constructors, its methods, its fields, and so on.
Therefore, every object belongs to a class and has a Class object. The Class object of any given object can be obtained via the getClass() method.
The isArray() method
The isArray() method of Class is used to check whether an object is an array or not. The method returns true if the given object is an array. Otherwise, it returns false.
Syntax
public boolean isArray();
Parameters
This method takes no parameters.
Example
import java.util.Arrays;public class Main {public static void main(String[] args){String stringObject = "educative";System.out.printf("Is %s an array - %s", stringObject, stringObject.getClass().isArray());System.out.println();int[] intArrayObject = new int[4];System.out.printf("Is %s an array - %s", Arrays.toString(intArrayObject), intArrayObject.getClass().isArray());}}
Explanation
- Line 1: We import the
Arraysclass from thejava.utilpackage. - Line 3: We define a class
Main. - Line 5: We define the
mainmethod of theMainclass. - Line 6: We define a string object
stringObject. - Line 7: We use the
isArray()method to determine ifstringObjectis an array. - Line 10: We define an integer array
intArrayObject. - Line 11: We use the
isArray()method to determine ifintArrayObjectis an array.