Java arrays are used to store a collection of variables of the same type. They are objects that have a fixed size and can store data of primitive types such as int, float, double, char, etc. as well as objects of any class type.
Declaring an Array:
To declare an array, you need to specify its data type, followed by square brackets [] and the array name. For example, to declare an array of integers named “myArray,” you would write:
int[] myArray;
Initializing an Array:
To initialize an array, you need to allocate memory for it using the new keyword. You can either initialize the array with specific values at the time of creation or assign values to it later.
// Initialize an array with specific values int[] myArray = {1, 2, 3, 4, 5}; // Initialize an empty array with a specific size int[] myArray = new int[5]; // Assign values to the array later myArray[0] = 1; myArray[1] = 2; myArray[2] = 3; myArray[3] = 4; myArray[4] = 5;
Accessing Elements of an Array:
You can access the elements of an array using the index number, which starts at 0 and ends at the length of the array minus one. For example, to access the first element of the “myArray” array, you would write:
int firstElement = myArray[0];
Iterating over an Array:
To iterate over an array, you can use a for loop that starts at 0 and ends at the length of the array minus one. For example:
for (int i = 0; i < myArray.length; i++) { System.out.println(myArray[i]); }
Multidimensional Arrays:
Java also supports multidimensional arrays, which are essentially arrays of arrays. To declare and initialize a two-dimensional array, you would write:
int[][] myArray = {{1, 2, 3}, {4, 5, 6}};
To access an element in a two-dimensional array, you need to specify both the row and column index:
int element = myArray[0][1]; // this would retrieve the element at row 0, column 1 (which is 2)
Java also supports higher-dimensional arrays, but they are less common in practice.
Arrays are an important data structure in Java and are used extensively in programming. They provide a convenient way to store and manipulate data, and they are used in many algorithms and data processing applications.