简体   繁体   中英

Can array of primitive data type be instantiated?

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

Can array of primitive data type be instantiated?

Yes.

Does the new keyword in new int[20] instantiate or initiate?

In that example, it both instantiates the primitive array and initializes it 1 to the default value for the primitive type; ie zero for an array of a primitive numeric type and false for an array of boolean .

On the other hand:

int intArray[];

is declaring an array variable and not either initializing the variable, or instantiating an array. If that is a local variable declaration, the compiler won't let you use the variable until it is assigned to. If it is a field, then the variable will be default initialized to null ; ie no array is instantiated.

Java does not allow a program to access a variable or array element that has not been initialized, either explicitly or by default initialization. This is a fundamental property of the language.


1 - The correct term is initialize NOT initiate . Initiate (in English) means either "to begin" (eg an action or process) or "to admit (someone) into a secret or obscure society or group, typically with a ritual.". It has no meaning in this context.

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 (eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM