Array java

Hello everyone!! Welcome to flower brackets blog. Today we are going to learn array java.

Array is a collection of similar type of elements that have contiguous memory location.

array java

For example, say you want to store 20 integers in an array, you can do it. But if you want to store 10 integers and 5 double values you can’t do it.

Also read – 2d array in java

  • Array index starts from 0. Arrays are dynamically allocated.
  • Also array is a static data structure and it contains homogeneous elements. It maintains type safety check.
  • Array contains a chain of elements stored under one variable name. Hence array occupies contiguous memory location (as you can see in the above figure).
  • array is an object. It contains primitive data type and objects of class.
  • primitive data type are stored in contiguous memory location and objects are stored in heap memory.

Create, initialize and access an array

One dimensional array : here elements are stored in an unbroken row. Here’s the syntax,

// one dimensional array
dataType[] arrNum;
dataType arrNum[];

Declaring float array,

int arr[];
int[] arr;

Declaring and allocating memory to array

arr = new datatype[size];

To allocate memory we have to instantiate an array like this using “new” keyword,

arr = new int[10];

After allocating memory elements in the array will be initialized to zero. Here are different data type array declaration,

byte byteArr[];
short shortArr[];
boolean boolArr[];
long longArr[];
float floatArr[];
double doubleArr[];
char charArr[];


Access array elements using for loop

public class SingleDimensionalDemo 
{
   public static void main(String[] args) 
   {
      // declare and instantiating an array
      int arrNum[] = new int[5]; 
      // initializing array
      arrNum[0] = 25; 
      arrNum[1] = 23; 
      arrNum[2] = 15; 
      arrNum[3] = 20; 
      arrNum[4] = 24;
      System.out.println("Single dimensional array : ");
      for(int a = 0; a < arrNum.length; a++) 
         System.out.println(arrNum[a]);
   }
}

Output :

Single dimensional array :
25
23
15
20
24


Array of objects

In the above java program we store primitive data types in array. Similarly we can also store objects in array.

Employee emp[] = new Employee[5];

public class Employee 
{
public int empID;
public String name;
Employee(int empID, String name)
{
this.empID = empID;
this.name = name;
}
}

public class ArrayObjectsDemo
{
public static void main(String[] args)
{
// declaring an array of integers
Employee[] emp;

// allocating memory for 5 objects of type Employee
emp = new Employee[5];

// initializing elements of the array
emp[0] = new Employee(101,"ajay");
emp[1] = new Employee(201,"vijay");
emp[2] = new Employee(301,"shikhar");
emp[3] = new Employee(401,"dhoni");
emp[4] = new Employee(501,"mandeep");

// accessing elements of the array
for(int a = 0; a < emp.length; a++)
{
System.out.println("index " + a + " : " + emp[a].empID + ", " + emp[a].name);
}
}
}

Output:

index 0 : 101, ajay
index 1 : 201, vijay
index 2 : 301, shikhar
index 3 : 401, dhoni
index 4 : 501, mandeep


ArrayIndexOutOfBoundsException

Compiler throws this exception when array object accesses an array with an index out its bound.

public class ArrayException 
{
public static void main(String[] args)
{
// declaring an integer array
int arrNum[] = new int[5];
// initializing elements
arrNum[0] = 11;
arrNum[1] = 12;
arrNum[2] = 13;
arrNum[3] = 14;
arrNum[4] = 15;
arrNum[5] = 16;
arrNum[6] = 17;
for(int a = 0; a <= arrNum.length; a++)
{
System.out.println(arrNum[a]);
}
}
}

Output :

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 5 at ArrayException.main(ArrayException.java:13)

In the above example I have declared integer array. Size of integer array is five.

Also read – Two dimensional array java program

I am initializing seven elements. This is not possible because size of integer array is 5 and I’m trying to assign seven elements.

So integer array will throw ArrayIndexOutOfBoundsException.


Multidimensional array

Multidimensional array is nothing but array of arrays. Let’s see how to declare and initialize multidimensional array,

Syntax

// declaring multidimensional array
dataType[][] studentMarks;
dataType[][]studentMarks;
dataType studentMarks[][];
// array of 3 rows and 3 columns
int studentMarks[][] = new int[3][3]; // two dimensional array
int studentMarks[][][] = new int [4][5][4]; // three dimensional array

In the above declaration you can see three and three in square brackets. This means three rows and three columns. We can initialize each element in two dimensional array like this,

// initializing two dimensional array
arr[0][0] = 22;
arr[0][1] = 21;
arr[0][2] = 18;
arr[1][0] = 15;
arr[1][1] = 25;
arr[1][2] = 23;
arr[2][0] = 20;
arr[2][1] = 19;
arr[2][2] = 16;

Each element therefore must be accessed by a corresponding number of index values.

public class MultiDimensionalArrayDemo 
{
   public static void main(String[] args) 
   {
      // declaring and initializing 2D array
      int arrNumber[][] = {{10,23,32},{22,42,52},{43,41,53}};
      // printing two dimensional array
      for(int a = 0; a < 3; a++)
      {
         for(int b = 0; b < 3; b++)
         {
            System.out.print(arrNumber[a][b] + " ");
         }  
         System.out.println();
      }
   }
}

Output :

10 23 32
22 42 52
43 41 53


Passing array to method

The advantage of passing array to method is that we can reuse the same logic on any array.

public class JavaArrayToMethod 
{
   public static void main(String[] args) 
   {
// declaring and initializing an array int arrayNumbers[] = {25,23,15,20,24}; add(arrayNumbers); // passing array } static void add(int arrDemo[]) { int total = 0; for(int a = 0; a < arrDemo.length; a++)
{
total += arrDemo[a]
}
System.out.println(total); } }

Output:

107


Return array from method

public class ReturnMethodDemo 
{
   public static void main(String[] args) 
   {
      // calling method 
      int arrNum[] = demo(); 
      // printing the values 
      for(int a = 0; a < arrNum.length; a++)
{ System.out.println(arrNum[a] + " ");
} } static int[] demo() { return new int[]{25,23,15,20,24}; } }

Output :

25
23
15
20
24


Clone of an array

Like variables we cannot copy single dimensional array using equal to operator (=). To copy an array clone() method is used.

Here new array contain copy of original array elements instead of reference. Hence “deep copy” is accomplished.

public class CloneArrayDemo 
{
public static void main(String[] args)
{
int arr[] = {25,23,15,20,24};
int arrClone[] = arr.clone();
// return false as deep copy is implemented
System.out.println(arr == arrClone);
for(int a = 0; a < arrClone.length; a++)
{
System.out.print(arrClone[a] + " ");
}
}
}

Output:

false
25 23 15 20 24

Similarly what happens in multidimensional array is, new array is created with each and every element having reference to original array but the cloned array will have only subarrays.

public class CloneArrayDemo 
{
public static void main(String[] args)
{
int arr[][] = {{25,23,15},{20,24}};
int arrClone[][] = arr.clone();
System.out.println(arr == arrClone);
// return true as shallow copy is implemented
System.out.println(arr[0] == arrClone[0]);
System.out.println(arr[1] == arrClone[1]);
}
}

Output:

false
true
true

Related Posts