When creating an array of a class in java there are three steps: Declaration, instantiation and initiation. But when creating an array of primitive data types, does the new keyword instantiate or initiate?
I found it confusing as in many places the word instantiate is used only for array of a class/classes. So, i want to know if the step of instantiating is also used for array of PRIMITIVE data type. Or, is it that the whole statement of initiating an array is as shown below.
int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to array
In Java , when we instantiate a primitive array (like new int[10]
), items in the array are initialized with default value of that primitive. (Default value for int
is 0
, default value for boolean
is false
etc.)
When we instantiate an object array (e.g. String
array), items in the array are initialized with null
.
See below program and its output.
public class PrimitiveArray
{
public static void main(String[] args)
{
int[] intArray = new int[10];
boolean[] booleanArray = new boolean[10];
String[] stringArray = new String[10];
System.out.println("intArray[3] = " + intArray[3]);
System.out.println("booleanArray[3] = " + booleanArray[3]);
System.out.println("stringArray[3] = " + stringArray[3]);
}
}
Output is:
intArray[3] = 0
booleanArray[3] = false
stringArray[3] = null