Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are arrays implemented in java?

Tags:

Arrays are implemented as objects in java right? If so, where could I look at the source code for the array class. I am wondering if the length variable in arrays is defined as a constant and if so why it isn't in all capital letters LENGTH to make the code more understandable.

like image 637
AFK Avatar asked Feb 15 '10 17:02

AFK


People also ask

How is array implemented?

Implementation of arrays performs various operations like push (adding element), pop (deleting element) element at the end of the array, getting the element from particular index, inserting and deleting element from particular index. // It store the length of array. this .

How are arrays of objects implemented in Java?

An Array of Objects is created using the Object class, and we know Object class is the root class of all Classes. We use the Class_Name followed by a square bracket [] then object reference name to create an Array of Objects.

How is an array created in Java?

You can make an array of int s, double s, or any other type, but all the values in an array must have the same type. To create an array, you have to declare a variable with an array type and then create the array itself. Array types look like other Java types, except they are followed by square brackets ( [] ).


2 Answers

Although arrays are Objects in the sense that they inherit java.lang.Object, the classes are created dynamically as a special feature of the language. They are not defined in source code.

Consider this array:

MySpecialCustomObject[] array; 

There is no such source code for that. You have created it in code dynamically.

The reason why length is in lower case and a field is really about the fact that the later Java coding standards didn't exist at the time this was developed. If an array was being developed today, it would probably be a method: getLength().

Length is a final field defined at object construction, it isn't a constant, so some coding standards would not want that to be in upper case. However in general in Java today everything is generally either done as a constant in upper case or marked private with a public getter method, even if it is final.

like image 192
Yishai Avatar answered Sep 28 '22 11:09

Yishai


For every Array we declare, corresponding classes are there in Java but it's not available to us.You can see the classes by using getClass().getName()

    int[] arr=new int[10];     System.out.println(arr.getClass().getName()); 

Output : [I

where "[" represents one dimension array and "I" represents Integer. Similarly, we can have

    [F for one-dimensional float arrays     [Z for one-dimensional boolean arrays     [J for one-dimensional long arrays     [[I for two-dimensional int arrays 

and so on.

like image 32
Bibhudatta Mishra Avatar answered Sep 28 '22 11:09

Bibhudatta Mishra