Determining If an Object Is an Array in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 09-Jan-2019 08:26:59
Advertisements