This question already has answers here:
Closed 3 years ago.
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.
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.