Array is a data structure. It is used to store many values of the same primitive data type or objects.
Arrays are used to store multiple values in a single variable, it saves the programmer from declaring separate variables for the values of same data type. Array is a reference data type or user defined datatype.
In an array the size has to be given when declaring an array. Once created the size of the array can’t be changed.
Array is a linear data structure, means that it stores all the elements in a continuous memory location.

To declare an array
datatype arrayname [] or datatype [] arrayname
int arr[] or int [] arr
To create an array
datatype arrayname []; = new datatype [array size]
int arr[] = new int[4];
Another way of creating the array is, directly giving values while declaring the array.
For Example:
int arr[]={4,5,7,8};
Here there is no need to give the size of the array, size will be automatically calculated from the elements in the curly bracket.
To initialize an array
Another way to initialize an array is
for (int i=0;i<arr.length;i++)
arr[i]=i;

All the array elements can be accessed using their index. Index of the array starts from zero. The last index of the array is size-1. The size of the array can be calculated using the data member length of the array class. The syntax for calculating the array size is
arr.length;

Write a program to declare , initialize and print an integer array.

class Array
 {
 public Static void main()
 {
 Scanner sc= new Scanner(system.in);
 int marks[]=new int[4];
 System.out.println(" Enter marks of four subjects");
 for (int i=0; i<4;i++)
 marks[i]=sc.nextInt();
 System.out.println(" The marks of four subjects are ");
 for (int i=0; i<4;i++)
 System.out.println(marks[i]);
 }
 }

Output:
Enter marks of four subjects
45
60
65
30
The marks of four subjects are
45
60
65
30

There are two types of arrays in java. Single dimensional array and Double dimensional array. In a single dimensional array the array elements are stored sequentially. In multi dimensional array the elements are stored in row and column based index, it is called matrix also.
There are two types of searching methods available for an array. Linear search and binary search.
For linear search program click this link.
https://java4school.com/linear-search
For Binary search program click this link.
https://java4school.com/binary-search

LEAVE A REPLY

Please enter your comment!
Please enter your name here