Arrays

Arrays are the collection of similar types of data items stored at contiguous memory locations. An array contains only elements of the same data type and has a fixed length. Each element in the array can be randomly accessed using its address or index position.

Why do we need Arrays?

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

for example, you would like to store the scores of 1000 students. It is not possible to create 1000 variables. But with arrays, you can store multiple values in a single variable.

Syntax:

//datatype[] variable_name = {value1, value2, value3, ...};
int[5] scores = {90,89,98,99,96};
/* int[] declaring an array of integers.
scores The name of the array variable.
{90, 89, 98, 99, 96}: This is the array initializer, 
enclosed in curly braces {}. 
Inside the curly braces, 
you specify the values you want to store in the array.
*/
System.out.println("Element of index 1: " + scores[1]);
// datatype[] variable_name = new datatype[size];
int[] scores = new int[100];
/* int[] declaring an array of integers.
scores this is the name of the array variable. 
new int[100] A new integer array with a length of 100.
it allocates memory for an array that can hold 100 integer values. 
[100] specify the size or capacity of the array.
*/
scores[0] = 85; // Assign the value 85 to the first element of the array

Arrays are a fundamental and versatile data structure in programming, providing efficient storage and retrieval for ordered collections of elements. Arrays are one type of data structure used to store collections of data.