Determining If an Object Is an Array in Java


In order to determine if an object is an Object is an array in Java, we use the isArray() and getClass() methods.

The isArray() method checks whether the passed argument is an array. It returns a boolean value, either true or false

Syntax - The isArray() method has the following syntax -

Array.isArray(obj)

The getClass() method method returns the runtime class of an object. The getClass() method is a part of the java.lang.Object class.

Declaration − The java.lang.Object.getClass() method is declared as follows −

public final Class getClass()

The getClass() method acts as the intermediate method which returns an runtime class of the object, which enables the terminal method, isArray() to verify it.

Example

Let us see a program to check if an object is an array or not −

 Live Demo

public class Example {
   public static void main(String[] args) throws Exception {
      String str = "Hello";
      String atr[][]= new String[10][20];
      System.out.println("Checking for str...");
      checkArray(str);
      System.out.println("Checking for atr...");
      checkArray(atr);
   }
   public static void checkArray( Object abc) {
      boolean x = abc.getClass().isArray();
      if(x == true)
         System.out.println("The Object is an Array");
      else
         System.out.println("The Object is not an Array");
   }
}

Output

Checking for str...
The Object is not an Array
Checking for atr...
The Object is an Array

Updated on: 29-Jun-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements