Arrays
An array is a fixed collection that stores values of the same type in an ordered list. An array is an ordered collection of values of the same type. An array holds a fixed number of values. The length of the array is established when the array is created. The length can not be changed afterwards.
Arrays needs to be declared and then allocated before they can be used.
Declaring Arrays
The square brackets([]), denotes the variable as an array. numbers is an integer array. the syntax is as follows
data_type[] variable_name; //[] can either follow the data type
datatype variable_name[]; //or can be after the variable name
Array of int
int numbers[]; //can only hold values of type int
Array of strings.
String[] names; //can only holds values of type string
Allocating Memory
Memory needs to be allocated for the array. The syntax is as follows
variable_name = new data_type[size]; //size can only be of type integer
Allocate memory for array of ints
Allocate space in memory for five integer types.
int numbers = new int[5];
Allocate space in memory for array of strings
string[] names = new string[3];
Assigning values to items in the array
Each element in the array is called an element, and each element is accessed by its numerical index. The first index is zero.
String languages[] = new String[3];
languages[0] = "Java"; //first element is on index 0
languages[1] = "C++";
languages[2] = "JavaScript"; //last element in the array
Create and Allocate
Arrays offer an alternative syntax to create and allocate memory. This is a convenient for small arrays. Use the curly braces ({}) to enclose the values.
String[] languages = { "Java", "C++", "JavaScript" };
languages[0] = "Java Programming"; //Modify the first item