12

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]; 
3
  • 1
    Arrays are Objects in Java. Commented Jul 26, 2014 at 8:11
  • 11
    1. All arrays are objects. 2. Arrays of floats are not arrays of objects (so your "corrected" code will not compile) Commented Jul 26, 2014 at 8:13
  • 4
    How is this not a duplicate 6 years after Stack Overflow launched? Commented Jul 26, 2014 at 19:33

2 Answers 2

33

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
Sign up to request clarification or add additional context in comments.

10 Comments

Is there any replacement to "Object" in the statement "Object oa = new float[20];"? I understood your answer, but I am trying to mingle the line "Arrays are objects in java"
No, there isn't anything as generic as Object when it comes to primitives such as int, float, void, char...
Yes, there is. A float[] is of type float[], but also Object, Serializable and Cloneable.
@Chief Two Pencils: Thanks, now I understood from your comment that "float[]" is replacement for "Object" and it solved my doubt
@RajeshKumar, glad it helped but I was kinda just proving a point. JB's is better in regards to your question.
|
3

Basically, Object is a super class for all the objects in Java. So, making a reference of Object class and then using it as any other object is valid.

Object ob = new Integer(5);

Arrays in Java are nothing but the objects, so reference of Object class can be assigned an array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.