Array Java

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

Java Array

Array java : What is an array?

Array is a container object and it contain elements of similar data type. Array is a data structure where we store similar elements.

We can store only fixed set of elements in a java array. Array is a collection of similar type of elements that have contiguous memory location.

It is a collection of similar data types and is a container object that holds value of homogeneous type.

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

To create an array in java there are two types,

  • Single Dimensional Array
  • Multidimensional Array

Single dimensional array

Syntax

// java declare single dimensional array

dataType[] arrNum;  
dataType arrNum[];

// instantiating an array

arrNum = new datatype[size];

arrays java example

Let’s see an example of array in java,

public class SingleDimensionalDemo 
{
   public static void main(String[] args) 
   {
      // declare and instantiating an array in java
      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 java example : ");
      for(int a = 0; a < arrNum.length; a++) 
         System.out.println(arrNum[a]);
   }
}

Output :

Single dimensional array java example :
25
23
15
20
24


Declare, instantiate and initialize an array – array java

Let’s see how to initialize an array in java. 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.

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

Also Read – Learn Java Array

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

Now let’s see arrays java example,

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 java example : ");
      // printing array in java 
      for(int a = 0; a < arrayNumbers.length; a++) 
         System.out.println(arrayNumbers[a]);
   }
}

Output :

Single dimensional array java example :
25
23
15
20
24


Below we can see declaration of array with all data types

int[] arrayNumbers;

byte[] arrayBytes;

short[] arrayShort;

long[] arrayLong;

float[] arrayFloat;

double[] arrayDouble;

boolean[] arrayBoolean;

char[] arrayChar;

String[] arrayString;


Java array – store int values

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

array java

Here you can see the array which contains six elements and length of the 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.

Above array contains integer values. Array is a container object that holds a fixed number of elements of a single type.

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

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

Now, let’s see how to initialize an array in java,

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. Let’s see an example,

public class ArrayLength
{
   public static void main(String[] args)
   {
      // declare array in java
      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

Here I will cover when array index out of bounds exception occur and let’s understand it by an example,

public class ArrayException 
{
   public static void main(String[] args) 
   {
      int arrNumbers[] = {25,23,15,20,24};  
      for(int a = 0; a <= arrNumbers.length; a++)
      {  
         System.out.println(arrNumbers[a]);
      }
   }
}

Output :

25
23
15
20
24
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at ArrayException.main(ArrayException.java:8)

Above you can see the output of this program. 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.


Arraycopy() method

Here I will cover how to copy elements from source array to destination array. 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;
)

Now let’s see an example on java arraycopy,

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 click below links,

2d array in java.

Two dimensional array java program.


Jagged array in java

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

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

Here I will cover multidimensional array.

array java

Let’s see how to declare and initialize multidimensional array,

Syntax

// declaring multidimensional array in java

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 Method In Java

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

Let’s see an example below

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

Ok come let us learn 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.

We will see an example,

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

Here we are going to learn 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 the array while passing it to the method. It should be passed as an argument of a method.

So now let’s see how to declare an anonymous array and example,

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.

conclusion

So this is all about array java. I hope you have understood the concept of array in java very well.

You can subscribe to my blog flower brackets if you haven’t already.

Do share this post if you like!!!!!

You May Also Like