4

Consider the following code:

Object obj = {};

This results in the following error:

Type mismatch: cannot convert from Object[] to Object

However, according to the Java standard every Array is an Object:

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.

Besides that, the following snippet compiles without any problems:

Object [] arr = {};
Object obj = arr;

Question: what am I missing in the first code sample, i.e. why is not it valid?

P.S.: I'm almost sure that somebody already asked this question, because it seems so basic. However, I could not find any useful results neither here, nor in Google (maybe because square brackets are ignored in the search?). If there is a duplicate, which I missed, then please feel free to close my question. For the records, I checked the following questions. While their title seemed promising, they were all dealing with other kinds of issues, or did not contain the answer to my question:

Community
  • 1
  • 1
Attilio
  • 1,624
  • 1
  • 17
  • 27

1 Answers1

0

In-line array initialization can only be used for array type declarations - it's part of the syntax of the language.

In java 8, this line

Object o = {};

does not give the compile error you report. Instead, it gives:

Array initializer not allowed here

Array initializers can only appear as the initial value of an array.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • @TimBiegeleisen: tried with casting, does not work either. – Attilio May 21 '16 at 10:44
  • 1
    do you have a reference for your statement? (This is what I suspect as well, but could not find any source to confirm it.) – Attilio May 21 '16 at 10:45
  • @Attilio In doubt, consult the Java language spec. I am sure that you find an answer there. – GhostCat May 21 '16 at 10:50
  • @Jägermeister: I tried searching in the JSL as well, but could not find anything explicitly. The closest I found is the following sentence in [Chapter 10.6 Array Initializers](https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.6): "Each variable initializer must be assignment-compatible (§5.2) with the array's component type, or a compile-time error occurs." From this, I can infer that `Object obj` does not have a 'component type' (if component type is what I think it is ;) ), but this statement is still not explicit for me. – Attilio May 21 '16 at 10:58