Saturday, January 11, 2020

Java Arrays

Arrays in Java

Array


An Array provides the ordered collection of objects. The members of an array can primitive data types or the objects of any class in Java. Arrays are implicit extensions of the Object class.

We can declare an Array, such as

  int arr1[]= {7,21,15,21,93,14,70};//Array Declaration
  int arr2[]=new int[15];           //Array Declaration
  int []arr3=new int[7];    //Array declaration

We need to specify the size(fix size) of the array to create an array.





Initializing an Array


When an array is created each element is set to its default value like numeric types are set to 0, the char type is set to '\u0000', the boolean is set to false and the reference types are set to null.

Advantages of Arrays

  • Easy to use
  • Efficient and fast
  • indexed/random Access 

Disadvantages of Arrays

  • Fixed-size(static data structure) 


public class ArrayTest {

 public static void main(String[] args) {
  
  int arr2[]=new int[15];           //Array Declaration
    for(int i=0;i<arr2.length;i++)
  {
   arr2[i]=(int)((Math.random())*99.9);
  }
  //Accessing Array
  for(int i=0;i<arr2.length;i++)
  {
   System.out.print(arr2[i]+"\t");
  }
 }

}

Output:
54 20 84 7 54 25 88 43 87 44 95 79 40 60 33 

Array of Objects

We can also create arrays of objects like primitive data types. For example

class Box{ 
  // create a class

 int h,w,l;
 public Box(int h, int w, int l) {//Constructor
  super();
  this.h = h;
  this.w = w;
  this.l = l;
 }

 public void displayVolume()//method to caculate volume
 {
  System.out.println("Volume "+ h*w*l);
 }
}

public class ArrayTest {

 public static void main(String[] args) {
 Box box[]=new Box[5];// create an Array of Boxes
 box[0]=new Box(10,21,13);//create five Boxes
 box[1]=new Box(11,19,44);//Add to Array box[]
 box[2]=new Box(21,17,26);
 box[3]=new Box(14,11,28);
 box[4]=new Box(17,22,19);

 for(Box b:box)
 {
  b.displayVolume();
 }
}

}

Output:

Volume 2730
Volume 9196
Volume 9282
Volume 4312
Volume 7106


The array of Arrays OR multi-dimensional Arrays 


We can create an array of arrays in Java(also known as multi-dimensional arrays), such as

double d[][]=new double[4][4];
int arr[][]=new int[4][];

The first or leftmost dimension of a multi-dimensional array must be specified, other dimensions can be left unspecified. Other dimensions may also vary in length.

int triangle[][]={
            {1},
            {1,1},
            {1,2,1},
            {1,3,3,1},
            };

For example,

public class ArrayTest {

  public static void main(String[] args) {
  char c[][]= {  //Multi-dimensional Arrays
    {'i'},{'l','o','v','e'},{'j','a','v','a'} 
  };

 //Accessing this array
 for(int i=0;i<c.length;i++)
 {
  for(int j=0;j<c[i].length;j++)
  {
   System.out.print(c[i][j]+"_");
  }
  System.out.println();
 }
}

}


Output:

i_
l_o_v_e_
j_a_v_a_



Video Tutorial