Java MCQ: How can you retrieve the length of an array using Java Reflection?
Answer:
Explanation:
The getLength()
method in the java.lang.reflect.Array
class is used to retrieve the length of an array using Java Reflection. This method is particularly useful when working with arrays of unknown types or dimensions at runtime.
Here’s an example of how to use getLength()
to retrieve the length of an array:
import java.lang.reflect.Array;
public class GetArrayLengthExample {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
int length = Array.getLength(array);
System.out.println("Array length: " + length);
}
}
In this example, an integer array is created, and the getLength()
method is used to obtain its length. The length is then printed to the console. The Array.getLength()
method can be used with any array type, making it a versatile tool for handling arrays reflectively.
The ability to work with arrays dynamically at runtime is an important feature of Java Reflection, allowing developers to write more generic and flexible code that can handle different data structures without knowing their specifics in advance.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html