JAVA ARRAYS:-


Normally, an array is a collection of similar type of elements which has contiguous memory location.

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.

. In java, all arrays are dynamically allocated.

. Arrays are stored in contagious memory.

. A java array variable can also be declared like other variables with[] after the data type.

. The variables in the array are ordered, and each has an index beginning from 0.

. Java array can also be used as a static field, a local variable, or a method parameter.


Advantages

  • Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
  • Random access: We can get any data located at an index position.

Disadvantages

  • Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in Java which grows automatically.

Types of Array in java

There are two types of array.

  • Single Dimensional Array
  • Multidimensional Array

Single Dimensional Array in Java

SYNTAX:

 
 dataType[] arr; (or)
 dataType  []arr; (or)
 dataType arr[];


EXAMPLE:

 public class example{

public static void main(String args[]){

int a[]= new int[5];

 int i;

 a[0]=10;

 a[1]=20;

 a[2]=30;

 a[3]=40;

 a[4]=50;

for(i=0;i<a.length;i++)

System.out.println(a[i]);

}

}

OUTPUT:-



Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java


   dataType[][] arrayRefVar; (or)

   dataType [][]arrayRefVar; (or)

   dataType arrayRefVar[][] ; (or)

   dataType []arrayRefVar[] ;


EXAMPLE:

public class example{  

public static void main(String args[]){  

int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; 

 for(int i=0;i<3;i++){  

 for(int j=0;j<3;j++){  

   System.out.print(arr[i][j]+" ");  

 }  

 System.out.println();  

}  

}

}  

OUTPUT: