Thursday 24 May 2018

How to check given object is an array or not?

An array is a series of elements of the same type placed in contiguous memory locations. Elements in the array are accessed by using index positions.

Example
char arr[] = {'H', 'E', 'L', 'L', 'O', 'J', 'A', 'V', 'A'};




‘java.lang.Class’ provided ‘isArray’ method, that return true if the given object is an array, else false.

public static boolean isArray(Object object) {
         return (object != null && object.getClass().isArray());
}

Find the below working application.

Test.java
package com.sample.test;

public class Test {

 public static boolean isArray(Object object) {
  return (object != null && object.getClass().isArray());
 }

 public static void main(String args[]) throws ClassNotFoundException {
  Object obj = new Object();
  int[] arr = new int[4];

  System.out.printf("Is obj array? %b\n", isArray(obj));
  System.out.printf("Is arr array? %b", isArray(arr));

 }
}

Output
Is obj array? false
Is arr array? True


No comments:

Post a Comment