# Java陣列元素

``````myID[0]   = 10;    // Assign  10  to the   first element of  myID
myID[1]   = 20;    // Assign  20  to the   second  element of  myID
myID[2]   = 30;    // Assign  30  to the   third  element of  myID
myID[3]   = 40;    // Assign  40  to the   fourth  element of  myID
myID[4]   = 50;    // Assign  50  to the   fifth element of  myID
``````

``````int temp  = myID[2]; // Assigns 30  to temp
``````

## 陣列長度

``````int[] myID = new int[5]; // Create an  array of  length 5
int len   = myID.length;      // 5  will be  assigned to len
``````

`length`是陣列物件的屬性。在未建立陣列物件之前，是不能使用它的`length`屬性的。通常，使用迴圈存取陣列的元素。

``````for (int i = 0 ; i < myID.length; i++)   {
myID[i] = (i + 1)  *  10;
}
``````

## 初始化陣列元素

``````int[]  intArray = new int[3];
``````

`bArray[0]``bArray[1]`初始化為`false`

``````boolean[] bArray  = new boolean[2];
``````

``````String[]  strArray = new String[2]
``````

``````Person[]  person = new Person[100];
``````

``````public class Main {
private boolean[] bArray = new boolean[3]; // An instance variable

public Main() {
for (int i = 0; i < bArray.length; i++) {
System.out.println("bArray[" + i + "]:" + bArray[i]);
}
}

public static void main(String[] args) {
int[] myID = new int[3]; // A local array variable
for (int i = 0; i < myID.length; i++) {
System.out.println("myID[" + i + "]:" + myID[i]);
}
String[] name = new String[3]; // A local array variable
for (int i = 0; i < name.length; i++) {
System.out.println("name[" + i + "]:" + name[i]);
}
}
}
``````

``````myID[0]:0
myID[1]:0
myID[2]:0
name[0]:null
name[1]:null
name[2]:null
``````