This shot discusses how to determine if the object is an array in Java.
Class
class in JavaJava 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.
isArray()
methodThe 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
.
public boolean isArray();
This method takes no parameters.
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());}}
Arrays
class from the java.util
package.Main
.main
method of the Main
class.stringObject
.isArray()
method to determine if stringObject
is an array.intArrayObject
.isArray()
method to determine if intArrayObject
is an array.