07 Arrays - mazawi/Teaching-Java GitHub Wiki
- An array is a sequentially ordered collection of variables, all having the same data type.
- Arrays serve various purposes, such as performing statistical calculations or portraying the dynamic state of a game.
- The data type can encompass any of Java's primitive types (int, short, byte, long, float, double, boolean, char), an array, or a class.
- Each variable within the array is referred to as an element.
- Indices are used to specify the position of each element within the array. Consider a scenario where we aim to store the names of 100 individuals. To achieve this, we can create an array of the String type with the capacity to hold 100 names:
String[] namesArray = new String[100];
However, it's crucial to note that the above array is restricted to accommodating precisely 100 names. In Java arrays, the number of values is inherently fixed, meaning the array size remains constant once established. This ensures a predictable and structured approach to managing data within the array.
Array Declaration and Instantiation:
Arrays, being objects in Java, involve a two-step process for creation:
-
Declaring a Reference:
- Declare a reference to the array using this syntax:
datatype[] arrayName;
- Example:
int[] numbers;
- Declare a reference to the array using this syntax:
-
Instantiating the Array:
- Utilize this syntax to instantiate the array:
arrayName = new datatype[size];
- Here,
size
is an expression evaluating to an integer, specifying the desired number of elements.
- Here,
- Example:
numbers = new int[5];
- Utilize this syntax to instantiate the array:
This distinction between declaration and instantiation facilitates a clear and systematic approach to working with arrays in Java, allowing for efficient memory allocation and dynamic usage.