Reputation: 151
like
public static student[] arr = new student[10];
now, student is a class with some instance variables name(String)
and age(int)
.
I wanna know that as soon as this line is executed what will happen??
Will all the ten references get memory or I have to allocate them individually?? What if tried to access student[5].age
?
I need to know the memory allocation status.. Thank You...............
Upvotes: 2
Views: 1502
Reputation: 10240
Only reference variables will be created, when you create an array of objects. In your case reference variables for student class.
In the following image, a set of reference variables are created. Then, you can point those reference variables to actual objects, later.
Upvotes: 2
Reputation: 9011
When the above statement is executed, JVM will create 10 contiguous memory location, each big enough to hold reference to student
. This array, however, will contain no references or null
if you will. When you execute statement like arr[0] = new student();
a student
object will be created on heap and its reference will be saved in arr[0]
. Remember that the array is also allocated on heap.
So once you have create 10 student
objects, each will be allocated somewhere on the heap but their references will be stored in arr
Upvotes: 3
Reputation: 26084
public static student[] arr = new student[10];
will allocate the memory for 10 students. These memory are filled with null.
So here you cant access student[5].age
because the reference to the actual object doesn't exist.
We need to create the Object reference individually like below
for(int i=0;i<10;i++){
student[i]= new Student();
}
if you are accessing student[5].age before creating the actual object reference you will end with NullPointerException.
Upvotes: 1
Reputation: 500963
Will all the ten references get memory or I have to allocate then individually?
You will get space for ten references. Those references will be initialized to null
. If you want them set to anything other than null
, you'll have to do it separately.
Upvotes: 0
Reputation: 122026
Yes
public static student[] = new student[10];
As soon as that line executes ,JVM
allocates memory for 10 student references
.
From official docs on Arrays, look at the flow.
// declares an array of integers
int[] anArray;
// allocates memory for 10 integers
anArray = new int[10];
// initialize first element
anArray[0] = 100;
Upvotes: 2