Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How array works internally in Java?

This query is posted to basically understand points like

  • An object is class instance or an array;

  • An array is a subclass of Object class;

  • Everything that is instantiated other than primitive is an object in Java.

Here is my understanding of working with arrays in Java.

Considering the below program,

/* dummy.java */
class C {
    private int i; 
    public C() {
        i = 1;
        System.out.println("Am in constructor");
    }
}
public class dummy {
    public static void main(String[] args) {
        C[] c = new C[2]; // Line 11
        c[0] = new C();
        System.out.println(c);
    }
}

An object of type class [LC is created in run-time after running,

C[] c = new C[2]; //Line 11

In the above code. class [LC is an immediate subclass of Object class. Reference variable c points to this object (shown in red boundary below) after running Line 12 in the above code. Reference variables sit in stack and an object of type class C will go in heap.

enter image description here

For a below change of line 11 & 12 in the above code

C[][] c = new C[2][2];
c[0][0] = new C();

will make the representation as shown below.

enter image description here

Is my understanding correct? If yes, Can you please explain more on usage of class [LC in run time to instantiate an object?

Note: C[].class gives the actual type in run-time, which is class [LC.

like image 652
overexchange Avatar asked Nov 01 '22 16:11

overexchange


1 Answers

To answer your question: yes, in Java (and C#), nearly everything is split into multiple discrete chunks of memory accessed by pointers. This not only include your bidimensional array but also any embedded object inside your object C. In C++, if you have an array (single dimensional or not) of 10 objects and each of these object contains 10 embedded objects, you can allocate all this with a single piece of memory. In C# and Java, you will have a minimum of 101 memory allocations for storing all this (if all of the embedded objects are simple objects) in the case of a mono-dimensional array and more in the case of a multi-dimensional array.

However, this explosion of pieces of memory shouldn't be seen a something very bad because it's free you of the difficulty of managing yourself the allocation of memory as you can have with C/C++ and in most cases, the power of any modern CPU is generally sufficient to pull it forward at a sufficient speed.

like image 68
SylvainL Avatar answered Nov 09 '22 08:11

SylvainL