Array in Java
Arrays are used to store multiple values in a single
variable, instead of declaring separate variables for each value. Java
array is an object which
contains elements of a similar data type. Additionally, The elements of an
array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java
array.
declaration: An "array
declaration" names the array
and specifies the type of its elements.
Initialisation : Initialisation is when you provide an initial value for a
variable.
Instantiation : Instantiation is where an object (class instance) is
created.
Syntax to Declare an Array in Java
1.
dataType[] arr;
2.
dataType []arr;
3.
dataType arr[]; data types : int, char float, string
Instantiation of an Array in Java
arr=new datatype[size];
declaration, instantiation and initialization
in same time
int a[]={33,3,4,5};
Example
1.
class ArrExample{
2.
public static void main(String[] args){
3.
int a[]=new int[4];
4.
a[0]=1;
5.
a[1]=2;
6.
a[2]=0;
7.
a[3]=4;
8.
for(int i=0;i<a.length;i++)
9.
System.out.println(a[i]);
10.
}
11. }
Syntax of for-each loop
for
(type var : array) {
statements using var;
}
Java Program to print the array elements using for-each loop
1.
class Arr1{
2.
public static void main(String []args){
3.
int arr[]={33,3,4,5};
4.
for(int i:arr)
5.
System.out.println(i);
6. }
}
Types of Arrays in Java
Java mainly supports two types of arrays:
-
Single-Dimensional Array
-
Multi-Dimensional Array
1. Single-Dimensional Array (1D Array)
Definition
A single-dimensional array stores data in a linear form (either row-wise or column-wise).
It can be visualized as a single row of elements.
Characteristics
-
Stores elements of the same data type
-
Accessed using a single index
-
Index starts from
0 -
Size is fixed once declared
Declaration Syntax
Example: Array Input and Output Program
Explanation
-
User enters number of elements
-
Elements are stored using a
forloop -
Elements are printed using another loop
2. Multi-Dimensional Array
Definition
A multi-dimensional array stores data in row and column format (matrix form).
It is also called an array of arrays.
Uses
-
Matrix operations
-
Table-like data storage
-
Mathematical computations
Declaration Syntax
Example: Matrix Addition Program
sir aaru pani haldinu
ReplyDelete