Creating arrays
Description
An array declaration includes brackets.
Explanation
You can provide values immediately or create a chosen size.
Example
int[] scores = {82, 91, 76};← Chapter 5 — Arrays, Memory & Methods
mixed
An array stores a fixed number of values of one type. Each value has an index, beginning at zero.
Arrays are useful when the size is known. Later, collections such as ArrayList provide more flexible resizing.
An array declaration includes brackets.
You can provide values immediately or create a chosen size.
int[] scores = {82, 91, 76};Use an index in brackets.
Valid indexes go from 0 to length - 1.
int first = scores[0];Accessing an invalid index causes ArrayIndexOutOfBoundsException. A loop condition using i < array.length is a safe, standard pattern.
public class ArrayDemo {
public static void main(String[] args) {
int[] scores = {82, 91, 76};
for (int score : scores) {
System.out.println(score);
}
}
}