Java Reference
In-Depth Information
Array elements are always initialized irrespective of the scope in which the array is created. Array elements of
primitive data type are initialized to the default value for their data types. For example, the numeric array elements are
initialized to zero, boolean elements to false , and the reference type elements to null . The following snippet of code
illustrates the array initialization:
// intArray[0], intArray[1] and intArray[2] are initialized to zero by default.
int[] intArray = new int[3];
// bArray[0] and bArray[1] are initialized to false.
boolean[] bArray = new boolean[2];
// An example of a reference type array.
// strArray[0] and strArray[1] are initialized to null.
String[] strArray = new String[2]
// Another example of a reference type array.
// All 100 elements of the person array are initialized to null.
Person[] person = new Person[100];
Listing 15-1 illustrates the array initialization for an instance variable and some local variables.
Listing 15-1. Default Initialization of Array Elements
// ArrayInit.java
package com.jdojo.array;
public class ArrayInit {
private boolean[] bArray = new boolean[3]; // An instance variable
public ArrayInit() {
// Display the initial value for elements of the instance
// variable bArray
for (int i = 0; i < bArray.length; i++) {
System.out.println("bArray[" + i + "]:" + bArray[i]);
}
}
public static void main(String[] args) {
System.out.println("int array initialization:");
int[] empId = new int[3]; // A local array variable
for (int i = 0; i < empId.length; i++) {
System.out.println("empId[" + i + "]:" + empId[i]);
}
System.out.println("boolean array initialization:");
// Initial value for bArray elements are displayed
// inside the constructor
new ArrayInit();
System.out.println("Reference type array initialization:");
 
Search WWH ::




Custom Search