Arrays in Java
Define Array:
An array is a collection of similar types of data elements stored in contiguous memory locations.
It is a data structure that can store a fixed-size sequential collection of elements of the same type.
Important Properties of Arrays:
1. Arrays are indexed, starting from 0.
2. Arrays have a fixed size, which is determined at the time of creation.
3. Arrays can hold primitive types as well as objects.
4. Arrays are stored in contiguous memory locations.
5. The size of an array cannot be modified once created.
6. The length property provides the total number of elements in the array.
Two Ways to Define an Array:
1. Declaration and initialization separately:
int[] arr;
arr = new int[5];
2. Declaration and initialization together:
int[] arr = {1, 2, 3, 4, 5};
Define 2D Array:
A 2D array is an array of arrays, also known as a matrix, where data is stored in rows and columns.
Declaration of a 2D Array:
1. Declaration only:
int[][] matrix;
2. Declaration with size:
int[][] matrix = new int[3][3];
3. Declaration with initialization:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};