Java Almanac and Examples Collection
Back to Data Structures
Arrays in Java are treated as Objects! Because an array is an object, its name is a reference to an array, it’s not the array itself.
The array is stored at an address elsewhere in memory, and the name holds only this address.
You need to keep track of a fixed amount of information and retrieve it sequentially.
Arrays can be used to hold any linear collection of data. The items in an array must all be of the same type.
You can make an array of any built-in type (like ints, booleans, etc.) or any object type.
If the the array is declared as Object[]
, then object references of any type can be stored in it without casting.
Example of usage
import java.util.Calendar;
public class ArrayDemo {
public static void main(String[] args) {
int monthLen1[]; // declare a reference
monthLen1 = new int[12]; // construct it
int monthLen2[] = new int[12]; // short form
// even shorter with initializiation
int monthLen3[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
final int MAX = 10;
Calendar days[] = new Calendar[MAX];
for (int i = 0; i < days.length; i++) {
days[i] = Calendar.getInstance();
}
// Two-Dimensional Arrays want a 10-by-24 array
int me[][] = new int[10][];
for (int i = 0; i < 10; i++) {
me[i] = new int[24];
}
// Remember that an array has a ".length" attribute
System.out.println(me.length);
System.out.println(me[0].length);
}
}