Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, why are arrays objects? Are there any specific reasons?

Tags:

java

arrays

Is there any reason why an array in Java is an object?

like image 324
giri Avatar asked Jan 05 '10 21:01

giri


People also ask

Why array is an object in Java?

Array is considered to be an object in Java. The reason behind this is that an array can be created using the 'new' keyword. The 'new' keyword/operator is always used to create an object. This is how an array is perceived as an object.

Is a Java array always 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).

Why is an array an object?

The Array Object. Arrays are data structures that store information in a set of adjacent memory addresses. In practice, this means is that you can store other variables and objects inside an array and can retrieve them from the array by referring to their position number in the array.

Why is it better to use objects instead of arrays?

Objects represent a special data type that is mutable and can be used to store a collection of data (rather than just a single value). Arrays are a special type of variable that is also mutable and can also be used to store a list of values.


2 Answers

Because the Java Language Specification says so :)

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.

So, unlike C++, Java provides true arrays as first-class objects:

  • There is a length member.
  • There is a clone() method which overrides the method of the same name in class Object.
  • Plus all the members of the class Object.
  • An exception is thrown if you attempt to access an array out of bounds.
  • Arrays are instanciated in dynamic memory.
like image 158
Pascal Thivent Avatar answered Oct 08 '22 01:10

Pascal Thivent


Having arrays be objects means that you can do operations with them (e.g., someArray.count('foo')) instead of just doing it against them (e.g., count(someArray, 'foo')), which leads to more natural syntax.

like image 44
Ignacio Vazquez-Abrams Avatar answered Oct 07 '22 23:10

Ignacio Vazquez-Abrams