In Java, array is a fundamental datastructure which are used to store multiple values in a single variable , instead of declaring separate variables for each value.
To declare an array , define the variable type with square brackets [ ] . Arrays in java are objects, and they implicitly inherit from the java.lang.Object class.
Key Characteristics of Arrays in Java :
- Fixed size : Once an array is created, it’s size cannot be changed .
- Indexed Access : Elements in array are accessed using a numerical index , starting from 0 for the first element .
- Homogeneous Elements : An array can only store elements of a single data type ( e.g. String, int or object of a specific class )
- Memory Allocation : Arrays are dynamically allocated using the new keyword and their memory is typically managed in the heap.
- Default Initialization : Elements of an array are automatically initialized to their default values . (e.g. 0 for numeric types , null for reference types , false for boolean types ) if not explicitly assigned .
Declaring and initializing Arrays :
- Declaration :
Declaring an array variable prepares the variable of array to hold an array, but it does not create the array itself .
Syntax:
dataType[ ] arrayName ;
Example: int [ ] employeeIds;
2. Instantiation (Creation ) : It allocates memory for the array elements.
Syntax :
arrayName=new dataType[size]; // Example : employeeIds=new int [15];
3. Declaration and Instantiation in one Step :
Syntax :
dataType[] arrayName = new dataType[ size ] ; //Example : int [ ] employeeIds=new int [15];
4. Initialization with Values :
We can also declare, instantiate and initialize an array with values in one step.
Syntax:
dataType[] arrayName = { employeeId1 , employeeId2 , ……} ; //Example : int[ ] employeeIds = {111,112,113,114,115};
Access the Elements of an Array :
We can access an array element by referring to the index number .
Example :
int [ ] employeeIds = {111,112,113,114,115};
System.out.println(employeeIds[0]);
//Output : 111
Change an Array Element
To change the value of a specific element , refer to the index number .
Example :
int [ ] employeeIds = { 111,112,113,114,115};
employeeIds[0] =123;
System.out.println(employeeIds[0]);
//OUTPUT : 123 instead of 111
Array Length :
To find out how many elements an array has , use the length property.
Example :
int [ ] employeeIds = { 111,112,113,114,115 };
System.out.println(employeeIds.length);
//OUTPUT : 5
The new Keyword :
We can also create an array by specifying its size with new keyword . This makes an empty array with space for a fixed number of elements, which we cxan fill later .
Example :
int [ ] employeeIds = new int[3] ;
employeeIds[0]=111;
employeeIds[1]=112;
employeeIds[2]=113;
System.out.println(employeeIds[0]); //Output : 111
