-1

How does instantiation work in this code:

// decleration
dataType[] arrayRefVar;

//instantiation - is it required?
arrayRefVar = new dataType[arraySize];   //A

arrayRefVar[0]=1;  //B
arrayRefVar[1]=2;

I am from a C++ background, so i don't really understand creation of objects/arrays with 'new'. I know it is for allocating memory to the array and returning reference. Will the creation of array take place automatically at B if line A is skipped?

Edit: Found a similar one, if anyone interested: Array initialization syntax when not in a declaration

Amith
  • 730
  • 6
  • 22

2 Answers2

2

This is just reference(pointer) declaration but not object creation

// decleration
dataType[] arrayRefVar;

new keyword specifies that new memory location for given Type has to be created. This step is your actual object creation not the above step.You are pointing the reference named arrayRefVar to the newely created object.

//instantiation -
arrayRefVar = new dataType[arraySize];   //A

Without step 2, you will get NullPointerException.Meaning your trying to assign value to an object which does not exist

Balaji Reddy
  • 5,576
  • 3
  • 36
  • 47
0

It will not. when you create an array, the java virtual machine allocated the needed space.

The compiler does this because of the keyword new.

dataType[] arrayRefVar;



arrayRefVar[0]=1;  //B
arrayRefVar[1]=2;

essentially, this code would try to access a data address (arrayRefVar[0]) that is used for something else/not used.

initializing the array allocates those addresses.

ItamarG3
  • 4,092
  • 6
  • 31
  • 44