Array Java

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

array java

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

Array is a container object. It contains elements of similar data type. Array is a data structure where we store similar elements.

Array is also known as static data structure because size of an array must be specified at the time of its declaration.


Types of array

  • Single Dimensional Array
  • Multidimensional Array

Single dimensional array

Syntax

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

// instantiating an array
arrNum = new datatype[size];

public class SingleDimensionalDemo 
{
   public static void main(String[] args) 
   {
      // declare and instantiating an array
      int arrNum[] = new int[5]; 
      // initializing array java
      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


Declare, instantiate and initialize an array

Array declaration in java is as below

// we can declare, instantiate and initialize an array in one line
int arrayNumbers[] = {25,23,15,20,24};

This is how we can declare an array of integers. Here “int” is the array’s type. “arrayNumbers” is array’s name.

Square brackets are special symbols indicating “arrayNumbers” variable can hold an array.

Also read – learn java array

Declaration does not actually create an array. It simply tells the compiler that this variable will hold an array of specified type.

public class SingleDimensionalExample 
{
   public static void main(String[] args) 
   {
      // declaring, instantiation and initializing
      int arrayNumbers[] = {25,23,15,20,24};
      System.out.println("Single dimensional array : ");
      // printing array
      for(int a = 0; a < arrayNumbers.length; a++) 
         System.out.println(arrayNumbers[a]);
   }
}

Output :

Single dimensional array  :
25
23
15
20
24


Below we can see declaration of array of all data types.

int[] arrayNumbers;
byte[] arrayBytes;
short[] arrayShort;
long[] arrayLong;
float[] arrayFloat;
double[] arrayDouble;
boolean[] arrayBoolean;
char[] arrayChar;
String[] arrayString;


Storing integer values

Let’s see how to store integer values in array.

array java

Here you can see array with six elements and length of array is six.

First index is zero and last index is five. In index two we have element 300 and at index four we have element 500.

Length of an array is established when array is created. After creating array length is fixed.

Each entry in an array is called an element. Each element is accessed by its index.

public class ArrayJavaDemo
{
   public static void main(String[] args)
   {
      // declaring an array
      int[] arrayNumber;
      // allocating memory for arrayNumber
      arrayNumber = new int[6];
      // initializing elements
      arrayNumber[0] = 100;
      arrayNumber[1] = 200;
      arrayNumber[2] = 300;
      arrayNumber[3] = 400;
      arrayNumber[4] = 500;
      arrayNumber[5] = 600;

      System.out.println("-----Java Array Example------");     
      System.out.println("Element at index zero - " + arrayNumber[0]);
      System.out.println("Element at index one - " + arrayNumber[1]);
      System.out.println("Element at index two - " + arrayNumber[2]);
      System.out.println("Element at index three - " + arrayNumber[3]);
      System.out.println("Element at index four - " + arrayNumber[4]);
      System.out.println("Element at index five - " + arrayNumber[5]);
   }
}

Output:

array java


Length of an array

Here we are going to learn how to find the length of the array. Here’s an example,

public class ArrayLength
{
   public static void main(String[] args)
   {
      // declare array
      short[] arrayNumber;
      // allocating memory for arrayNumber
      arrayNumber = new short[6];
      System.out.println("-------------Length of an array demo----------");
      System.out.println("The length of an array before initializing - " + arrayNumber.length);
      // initializing elements
      arrayNumber[0] = 100;
      arrayNumber[1] = 200;
      arrayNumber[2] = 300;
      arrayNumber[3] = 400;
      arrayNumber[4] = 500;
      arrayNumber[5] = 600;
      System.out.println("The length of an array after initializing - " + arrayNumber.length);
   }
}

Output:

Java Array


Array index out of bounds exception

Let’s understand by an example,

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

Output :

The length of an array - 5
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
	at ArrayException.main(ArrayException.java:14)

In the above example I have declared integer array. Size of the integer array is five and I am printing out the length of the integer array as you can see in the output.

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 the integer array will throw ArrayIndexOutOfBoundsException and exception is thrown at 14th line.


Arraycopy() method

To copy an array we use arraycopy() method of System class.

Syntax

public static void arraycopy
(  
   Object src, int srcPos, Object dest, int destPos, int length;
)

public class ArrayCopyDemo 
{
   public static void main(String[] args) 
   {
      // here we declare source array 
      char fromCh[] = { 'f', 'l', 'o', 'w', 'e', 'r', 'b', 'r', 'a', 'c', 'k', 'e', 't', 's' }; 
      // here we declare destination array 
      char toCh[] = new char[7]; 
      // copying array using System.arraycopy() method 
      System.arraycopy(fromCh, 1, toCh, 0, 7); 
      // printing destination array 
      System.out.println(String.valueOf(toCh)); 
   }
}

Output :

lowerbr


Two dimensional array

To learn two dimensional array in java with an example follow below links,

2d array in java.

Two dimensional array java program.


Jagged array in java

Creating an array with odd number of columns is called as jagged array. Let’s illustrate jagged array,

public class JaggedArray 
{
   public static void main(String[] args) 
   {
      // declaring two dimensional array with odd columns 
      int arrNum[][] = new int[3][]; 
      arrNum[0] = new int[14]; 
      arrNum[1] = new int[23]; 
      arrNum[2] = new int[32]; 

      // initializing jagged array 
      int count = 0; 
      for(int a = 0; a < arrNum.length; a++)
         for(int b = 0; b < arrNum[a].length; b++)
            arrNum[a][b] = count++;

      // printing jagged array 
      for(int a = 0; a < arrNum.length; a++)
      { 
         for(int b = 0; b < arrNum[a].length; b++)
         { 
            System.out.print(arrNum[a][b] + " "); 
         } 
         System.out.println(); 
      }
   }
}

Output :

0 1 2 3 4 5
14 15 16 17 18 19
37 38


Multidimensional array

array java

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];

In the above declaration you can see three and three in square brackets. This means three rows and four columns.

We can initialize each element in multidimensional array like this,

// initializing multidimensional array in java
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;

Multidimensional array is nothing but array of arrays. It is nothing but two or more sets of brackets.

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

Also read – cloning in java

In java programming, multidimensional array is an array whose components are themselves arrays.

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


Multidimensional array – using loop

Let us see an example on how to execute a multidimensional array using for loop,

public class MultidimensionalArrayLoop
{
   public static void main(String[] args)
   {
      int[][] arrEven = {{2,4,6},{8,10,12}};
      int row = arrEven.length;
      System.out.println("The number of rows is - " + row + "\n"); 
      for(int a = 0; a < row; a++)
      {
         int column = arrEven[a].length;
         System.out.println("The number of columns in a row - " + a + " is " + column);
         for(int b = 0; b < column; b++)
         {
            System.out.println("The element at " + "arrEven[" + a + "] " + "[" + b + "] - " + arrEven[a][b]);
         }
         System.out.println();
      }
   }
}

Output:

array java


Multidimensional string array

String[][] strNames = {{ "Apple", "Fruit" }, { "Green", "Color" }, { "Audi", "Car" }};

Here I have declared a string array which is multidimensional array. We can declare a multidimensional array using two or more brackets.

As you can see declaration above I have initialized multidimensional array and has three rows and two columns.

public class MultidimensionalStringArray
{
   public static void main(String[] args)
   {
      String [][] strNames = {{ "Apple", "Fruit" }, { "Green", "Color" }, { "Audi", "Car" }};
      System.out.println("The element at strNames[0][0] - " + strNames[0][0]);
      System.out.println("The element at strNames[0][1] - " + strNames[0][1]);
      System.out.println("\n");
      System.out.println("The element at strNames[1][0] - " + strNames[1][0]);
      System.out.println("The element at strNames[1][1] - " + strNames[1][1]);
      System.out.println("\n");
      System.out.println("The element at strNames[2][0] - " + strNames[2][0]);
      System.out.println("The element at strNames[2][1] - " + strNames[2][1]);
   }
}

Output:

array java


Multidimensional string array – using for loop

public class MultidimensionalStringLoop
{
   public static void main(String[] args)
   {
      String [][] strNames = {{ "Apple", "Fruit" }, { "Green", "Color" }, { "Audi", "Car" }};
      int row = strNames.length;
      System.out.println("The number of rows is - " + row + "\n"); 
      for(int a = 0; a < row; a++)
      {
         int col = strNames[a].length;
         System.out.println("The number of columns in row " + a + " is - " + col);
         for(int b = 0; b < col; b++)
         {
            System.out.println("The element at " + "strNames[" + a + "]" + "[" + b + "] - " + strNames[a][b]);
         }
         System.out.println();
      }
   }
}

Output:

array java


How to pass java array to method

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

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

Output:

15


How to return array from method?

In java we can return array from method. Here’s the example,

public class ReturnMethod 
{
   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


Anonymous array in java

Anonymous array in java can be initialized and created without name. Anonymous array can be used only once.

You don’t have to declare array while passing it to the method. It should be passed as an argument of a method.

new int[] { 2, 4, 6, 8, 10};  // anonymous integer array 
new char[] {'a', 'b', 'c', 'd', 'e'); // anonymous character array
new String[] {"Flower", "brackets", "code"}; // anonymous String array
new int[][] {{20, 23}, {18, 21, 24}}; // anonymous multidimensional array


public class AnonymousArray 
{
   public static void main(String[] args) 
   {
      // here we pass anonymous array to method
      System.out.println("Anonymous array in java : ");
      anonymousMethod(new int[]{25,23,15,20,24}); 
   }

   // creating method which accepts array as parameter 
   static void anonymousMethod(int arrNum[])
   { 
      for(int a = 0; a < arrNum.length; a++) 
         System.out.println(arrNum[a]); 
   }
}

Output :

Anonymous array in java :
25
23
15
20
24


Addition of two matrices

public class AddTwoMatrices
{
   public static void main(String[] args)
   {
      // here we are creating two matrices
      int x[][] = {{2, 4, 6},{1, 3, 5}};
      int y[][] = {{2, 4, 6},{1, 3, 5}};

      // creating another matrix to store values
      int z[][] = new int[2][3];

      // now adding and printing values using for loop    
      System.out.println("Addition of two matrices - ");
      for(int a = 0; a < 2; a++)
      {
         for(int b = 0; b < 3; b++)
         {
            z[a][b] = x[a][b] + y[a][b];
            System.out.print(z[a][b] + " ");
         }
         System.out.println();
      }
   }
}

Output:

Addition of two matrices –
4 8 12
2 6 10


Advantages and disadvantages of array

AdvantagesDisadvantages
Array makes the code optimized. Sorting and retrieving the data is easy.We can store only fixed size of elements. Array does not grow its size at runtime.
To get data located at any index position is easier.Array structure is static. Memory allocated to an array can't be decreased or increased.
Array represents multiple data items of same type using only single nameWe must know in advance that how many elements are to be stored.
Array can be used to implement data structures like linked lists, queues, trees, graphs, stacks etc.Array elements are stored in consecutive memory locations. So insertion and deletion are difficult and time consuming.

Related Posts