Array:
An array is a data structure used to store multiple values of the same type in a single variable, instead of declaring separate variables for each variable.
i.e, int mark1=50;
int mark2=60;
int mark3=90;
you can store as,
int[] marks={50,60,70};
this is known as array object.
Keypoints:
Fixed size-Once created, the size of the array cannot be changed.
Homogeneous data-Stores only elements of the same data types.
Index based-Elements are stored in contiguous memory locations and can be accessed using an index (starting from 0).
First element-> index 0.
Second element-> index length - 1.
Objects in java->Arrays are objects stored in heap memory.
Declaring an array:
There are three steps,
1)Declaration (telling the compiler the type)
int[] marks;
int marks[];
2)Instantiation (allocating memory)
marks = new int[3]; (create array of size 3).
3)Initialization (assigning values)
marks[0]=90;
marks[1]=98;
marks[2]=80;
or, directly in one line
int[] marks={90,98,80};
Uses of Arrays:
- Storing multiple values efficiently->Instead of creating many variables, we can store values in a single structure. This saves memory and makes code cleaner.
- Easy access using index->Arrays allow direct access to any element using its index.
- Iterating with loops->Arrays can be traversed easily with for or for each loops.
- Used for grouping similar data->Useful when handling large amounts of homogeneous data (same type).eg, storing salaries, student marks, ages, etc.
- Foundation for data structure->Arrays are the base for advanced structure like:
- String (internally character arrays).
- Array List, vector (dynamic array).
- Matrices (2D arrays) for mathematical computations.
- Performance (fast access)->Since arrays use contiguous memory and indexing, accessing elements is very fast (0(1) time complexity).
- Multi=dimensional data representation->Arrays are used to represent tables, grides or matrices.
Top comments (0)