Java Reference
In-Depth Information
String[] name = new String[3]; // A local array variable
for (int i = 0; i < name.length; i++) {
System.out.println("name[" + i + "]:" + name[i]);
}
}
}
int array initialization:
empId[0]:0
empId[1]:0
empId[2]:0
boolean array initialization:
bArray[0]:false
bArray[1]:false
bArray[2]:false
Reference type array initialization:
name[0]:null
name[1]:null
name[2]:null
Beware of Reference Type Arrays
Array elements of a primitive type contain values of that primitive type, whereas array elements of a reference type
contain the reference of objects. Suppose you have an int array of
int[] empId = new int[5];
Here, empId[0] , empId[1]...empId[4] contain an int value.
Suppose you have an array of String, like so:
String[] name = new String[5];
Here, name[0], name[1]...name[4] may contain a reference of a String object. Note that the String objects, the
elements of the name array, have not been created yet. As discussed in the previous section, all elements of the name
array contain null at this point. You need to create the String objects and assign their references to the elements of
the array one by one as shown:
name[0] = new String("name1");
name[1] = new String("name2");
name[2] = new String("name3");
name[3] = new String("name4");
name[4] = new String("name5");
 
Search WWH ::




Custom Search