1

Recently when I do some practice on LeetCode,I find some trick solution.It use an Object o to reference an arrayObject o = new Object[]{null,null};,I guess maybe it's because in java everything is object.But when I tried this way,it went wrong.Object o3 = {1,2};So I tried every way to initialization a array and I want to see the difference,like these

int arr[] = {1,2};
Object o = arr;
Object o1 = new int[2];
Object o2 = new int[]{1,2};
Object o3 = {1,2};

Only the o3 will compile an error.I don't know if it's because the way of initialization.I know when I use static initialization it will allocate memory first,when use dynamic initialization it will not.Any other differences between them cause this error?When I use new to create a array.what did it do in jvm?Thanks in advance.

M Chen
  • 133
  • 1
  • 3
  • 15

1 Answers1

4

The initializer {1,2} is shorthand for new int[] {1,2}. This shorthand can only be used as an initializer for a variable of type int[].1 For instance, while the following works:

int arr[] = {1,2};

this doesn't:

int arr[];
arr = {1,2}; // ERROR

Instead, you would need to use:

int arr[];
arr = new int[] {1,2};

Similarly, you can use:

Object o3 = new int[] {1,2};

P.S. The above applies to static as well as instance fields, and also to local variables. Java doesn't have such a distinction as "static vs. dynamic initialization". That's more C++ terminology.

 1Well, it could also be for a variable of type byte[], long[], float[], Integer[], etc., for which the literals 1 and 2 are assignment compatible. See the Section 10.6 of the Java Language Specification.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • `{..}` literal array creation can be also performed with any reference type. Like: `String[] strings = {"one", "two"};` – Giorgi Tsiklauri Aug 15 '21 at 09:10
  • @GiorgiTsiklauri - You are right, of course. Such arrays can be of any element type at all, whether primitive or reference. It seemed to me that OP was specifically interested in arrays initialized with integer literals, which is why I worded my response the way I did. – Ted Hopp Aug 15 '21 at 10:57