-1
int arr[] = new int[2];
Object obj = arr;

The above code is valid but writing

Object obj[] = new Object[2];
int arr = obj;

is giving compile time error. Why? I am totally new to Java; can anybody explain?

arshajii
  • 127,459
  • 24
  • 238
  • 287
Shashank Agarwal
  • 1,122
  • 1
  • 8
  • 24

4 Answers4

1

The first one is valid because in Java : An array is an Object.

Arrays (The Java Tutorials) :

An array is a container object that holds a fixed number of values of a single type.

But, the second one, Object array is not an int, this is why it fails.

earthmover
  • 4,395
  • 10
  • 43
  • 74
0

Arrays in Java are objects, so the first snippet is valid. An array of objects, on the other hand, is certainly not an int, so the second snippet fails. Ask yourself: what would you expect arr to hold if that snippet were to compile?

From JLS §10:

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).

(emphasis mine)

arshajii
  • 127,459
  • 24
  • 238
  • 287
0

All Arrays are Objects. But all Objects are not arrays/ints.

int arr[]=new int[2];
Object obj=arr;// valid . an int array is also an Object

Object obj[]=new Object[2];
        int arr=obj; // an int is not an Object array
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

In the first case the array you create inherits from Object, so it works as expected.

In the second case, an integer in Java is a primitive type and you try to assign an Object. A primitive type is not an Object so it will never work.

fonZ
  • 2,428
  • 4
  • 21
  • 40