Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is declaring an array as an object correct in Java?

Tags:

java

The following expression compiles:

Object oa = new float[20]; 

How is this expression valid?

As per my opinion, the correct syntax would be

Object [] oa = new float[20]; 
like image 646
Rajesh Kumar Avatar asked Jul 26 '14 08:07

Rajesh Kumar


1 Answers

Arrays are objects in Java. So an array of floats is an object.

BTW, Object o = new Object[20]; is also valid, since an array of objects is an object.

Also note that Object[] oa = new float[20]; is invalid, since primitive floats are not objects, and an array of floats is thus not an array of objects. What would be correct is

Object[] oa = new Float[20];

Regarding arrays, since they are objects, they have all the methods of java.lang.Object. They also have a public final attribute length, and they are Cloneable and Serializable:

Object o = new float[20];
System.out.println("o instanceof Serializable = " + (o instanceof Serializable)); // true
System.out.println("o instanceof Cloneable = " + (o instanceof Cloneable)); // true
like image 142
JB Nizet Avatar answered Sep 30 '22 08:09

JB Nizet