
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Array Dimensions in Java
In order to get Array Dimensions in Java, we use the getClass(), isArray() and getComponentType() methods with decision making in combination with iterative statements.
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 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 getComponentType() method returns the Class denoting the component type of an array. If the class is not an array class this method returns null.
Declaration − The java.lang.Class.getComponentType() method is declared as follows −
public Class<?> getComponentType()
Let us see a program to get the dimensions of an array in Java −
Example
public class Example { public static int dimensionOf(Object arr) { int dimensionCount = 0; Class c = arr.getClass(); // getting the runtime class of an object while (c.isArray()) // check whether the object is an array { c = c.getComponentType(); // returns the class denoting the component type of the array dimensionCount++; } return dimensionCount; } public static void main(String args[]) { String[][][] array = new String[7][9][8]; // creating a 3 dimensional String array System.out.println(dimensionOf(array)); } }