JAVA DAY 5
8. Array
● 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 static linear data structure where we store similar
elements.
● We can store only a fixed set of elements in a Java array.
● Arrays in Java are index-based, the first element of the array is
stored at the 0th index, the 2nd element is stored on the 1st
index and so on.
● In Java, an array is an object of a dynamically generated class.
● Java array inherits the Object class and implements the
Serializable as well as Cloneable interfaces.
Advantages
o Code Optimization: It makes the code optimised, we can
retrieve or sort the data efficiently.
o Random access: We can get any data located at an index
position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the
array. It doesn't grow in size at runtime.
o To solve this problem, a collection framework is used in Java
which grows automatically.
Types of Arrays in java
There are three types of array.
o Single Dimensional Array
o Multidimensional Array
o Jagged Array
Single Dimensional Array in Java
Syntax
dataType[] a;
dataType []a;
dataType a[];
Instantiation
arrayRefVar=new data type[size];
Example:
Declaration, Instantiation, and Initialization of Java Array
We can declare, instantiate, and initialise the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
Example:
public class basic
{
public static void main(String[] args)
{
int c[]= {10,20,30,40,50};//initialization
for(int i=0;i<c.length;i++)
{
System.out.println(c[i]);
}}}
Multidimensional Array in Java
In this array data is stored in row and column-based index (also
known as matrix form).
Syntax
dataType[][] a; (or)
dataType [][]a; (or)
dataType a [][]; (or)
dataType []a [];
Instantiate
int arr[]=new int[3][3];//3 row and 3 column
Example
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example:
class Testarray3
{
public static void main(String args[])
{
//declaring and initialising 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Output