-2

Below expression is having no issue-

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

but below two have compile time issue-

Integer i = new int[] { 1, 2, 3 };
        int j = new int[] {1,2,3};

why?

OldProgrammer
  • 12,050
  • 4
  • 24
  • 45
  • 2
    Java motto: everything is an Object – jhamon Apr 07 '22 at 15:45
  • Does this answer your question? [They say in java "every thing is an object". Is that true?](https://stackoverflow.com/questions/11844012/they-say-in-java-every-thing-is-an-object-is-that-true) – jhamon Apr 07 '22 at 15:49
  • int[] is of type Object but int[] is not of type Integer – isaace Apr 07 '22 at 16:07

1 Answers1

2
var array = new int[]{1,2,3}

is of type int[], not an integer.

In Java, an array has a superclass of Object. Hence assigning that array to an Object is correct (if practically useless)

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • Hi @brain Agnew, thanks for your reply, but I am still not clear. for code. Number n = new Integer[] {1,2,3}; Number is the parent class but object n is still not able to hold the Integer array and asks to declare array of Number(i.e. Number[] n) instead of Number. – sushil kumar gupta Apr 07 '22 at 16:08
  • 1
    A Number is *not* an array of Numbers. Your array contains a collection (not a Java collection, to be clear with my terminology). Integer j could be of the value 1 OR 2 OR 3. But an array could have *all* those values, and to get an individual number you have to decide which one you want – Brian Agnew Apr 07 '22 at 16:23