blog

Home / DeveloperSection / Blogs / Array in Java

Array in Java

Manoj Pandey2004 27-Apr-2015

The array is a collection similar data type.  Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.


Array in Java


Creating Arrays:

dataType[] arrayRefVar;
arrayRefVar = new dataType[arraySize];
or
dataType[] arrayRefVar = {value0, value1, ..., valuen};
Example -:   double[ ] myList = new double[10];


Types of Array in java

There are two types of array.

  • Single Dimensional Array
  • Multidimensional Array

Example of Single Dimensional array

class Testarray{ 

publicstaticvoid main(String args[]){ 

 

int a[]=newint[5];//declaration and instantiation 

a[0]=10;//initialization 

a[1]=20; 

a[2]=70; 

a[3]=40; 

a[4]=50; 

 

//printing array 

for(int i=0;i<a.length;i++)//length is the property of array 

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

 

}

 

     

Output-:  10   20    70     40     50

 

Multidimensional array in java

Declare of multidimensional array: dataType[][] arrayRefVar; (or) 

dataType [][]arrayRefVar; (or)  
dataType arrayRefVar[][]; (or) 
dataType []arrayRefVar[];
Example-:  int[][] arr=new int[3][3];  //3 row and 3 column 
Initialized multidimensional array
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 of multidimensional array

class Sample {

public static void main(String args[]) {

//declaring and initializing 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(); 

}

}


Example of the array using for loop

public class Sample {

 

   public static void main(String[] args) {

      double[] myList = {1.9, 2.9, 3.4, 3.5};

 

      // Print all the array elements

      for (double element: myList) {

         System.out.println(element);

      }

   }

}

Output-: 

Advantage of Java Array
Disadvantage of Java Array

1.9

2.9

3.4

3.5


Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.


Random access: We can get any data located at any index position.


Size Limit: We can store the only 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.


Updated 23-Feb-2018

Leave Comment

Comments

Liked By