Is an array a primitive type or an object in Java?
An array in Java is an object. Now the question how is this possible? What is the reason behind that? In Java, we can create arrays by using new operator and we know that every object is created using new operator. Hence we can say that array is also an object. Now the question also arises, every time we create an object for a class then what is the class of array?
- In Java, there is a class for every array type, so there’s a class for int[] and similarly for float, double etc.
- The direct superclass of an array type is Object. Every array type implements the interfaces Cloneable and java.io.Serializable.
- In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array.
For every array type corresponding classes are available and these classes are the part of java language and not available to the programmer level. To know the class of any array, we can go with the following approach:
// Here x is the name of the array.
System.out.println(x.getClass().getName());
public class Test
{
public static void main(String[] args)
{
int [] x = new int [ 3 ];
System.out.println(x.getClass().getName());
}
}
|
Output:
[I
NOTE:[I this is the class for this array, one [ (square bracket) because it is one dimensional and I for integer data type.
Here is the table specifying the corresponding class name for some array types:-
Array type Corresponding class Name
int[] [I
int[][] [[I
double[] [D
double[][] [[D
short[] [S
byte[] [B
boolean[] [Z
In Java programming language, arrays are objects which are dynamically created, and may be assigned to variables of type Object. All methods of class Object may be invoked on an array.
public class Test {
public static void main(String[] args)
{
System.out.println(args instanceof Object);
int [] arr = new int [ 2 ];
System.out.println(arr instanceof Object);
}
}
|
Output:
true
true
Reference : https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html
Last Updated :
11 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...