What is array in java

Array in java

What is array in java

We will be using array a lot in our projects. Array is common in all programming languages, it’s syntax may be different but concept is same. In this tutorial, we will cover the concept of array in java. How we can implement different types of array in java programming.

What is array and how it actually works

An array is basically used to store two things in java either primitive values of the same type like int, char, float etc and references (reference to the actual object).

Creation of array in java is same as you create an object. When you create an object it’s reference is returned and stored to the reference variable. Same thing applies to the array in java.

Look at the basic syntax of array.

int a[] = new int[2];
a[0] = 22;
a[1] = 23;

Look at the above syntax. Here, “a” basically a reference variable of type int. This reference variable will hold the reference of array object. See below diagram of internal memory allocation.

Array in java

We have created an array of integer type. Now we told JVM to allocate two memory slot in heap area to store values by using new keyword as “new int[2]”. Now JVM will create an object in heap area and that object will hold integer values. After JVM creates the object of integer array, it passes the reference id to the reference variable as shown in the diagram above.

Now you can store and retrieve the values by using the index. Index is the main part of an array. Index is the location of the element at a particular location in array. Array always starts with the index 0 and up to the given size.

Some important things about Array

  1. Array basically is an object.
  2. You can only create fixed size of array, once initialized you can not change the size.
  3. An array can contain similar type of elements. It can not hold different types of elements.
  4. You can access and store the elements with the help of index, which is the location of element in array.
  5. Index always starts with 0 to nth element.
  6. Each element in array have default values.
  7. If you will try to access or add an element beyond the size of an array, you will get exception at run time.
  8. You can get the size of an array at run time by using “length” property of array. (array.length);

Types of array

There nothing like type of array in java or in any other programming language. This is the concept of how we implement an array. So by concept, we can divide an array in two types as below :

  1. Single Dimensional Array.
  2. Multi Dimensional Array.

Let’s discuss both of them with examples.

Single Dimensional Array

By definition, a single dimensional array is a type of linear array. A single dimensional array store the elements in either single row or column.

Syntax to represent single dimensional array

We can initialize single dimensional array in different ways but all of them do the one thing.

int a[] = new int[size];
int[] a = new int[size];
int []a = new int[size];

Each of the statements above are valid, you can use any of them to initialize an array in java. Let’s now create an example of single dimensional array.

class ArrayDemo {

     public static void main(String arg[]) {

         int[] a = new int[10];

         for(int i=0; i<a.length; i++) {
              a[i] = ((i+1) * 5);
         }

         for(int i=0; i<a.length; i++) {
              System.out.println("Value of a[" + i + "] : " + a[i]);
         }

     }
}
Output :
Value of a[0] : 5
Value of a[1] : 10
Value of a[2] : 15
Value of a[3] : 20
Value of a[4] : 25
Value of a[5] : 30
Value of a[6] : 35
Value of a[7] : 40
Value of a[8] : 45
Value of a[9] : 50

Loot at the above example, we created an array of size 10. After that, we used for loop in order to initialize values to an array using index. Note*: we started loop from zero, reason is that array always store values from zero index.

Now same way, we used for loop to access it’s elements from an array using index from zero.

Note*: you can access the size of an array by using it’s default property “length”. Which returns the actual size of an array not starting from zero.

Initializing the values of array using literals

You can also initialize an array using literals in java as below.

class ArrayDemo {

     public static void main(String arg[]) {

         int[] a = {1,3,4,2};

         for(int i=0; i<a.length; i++) {
              System.out.println("Value of a[" + i + "] : " + a[i]);
         }
 
         // Same way you can initialize string, char, float, double
         // char[] c = {'a','b','c'};
         // double[] d = {23.0, 22.0};
         // String[] s = {"Welcome", " to", " Array"};

     }
}
output:
Value of a[0] : 1
Value of a[1] : 3
Value of a[2] : 4
Value of a[3] : 2

Multi dimensional Array

As per definition, you can say multi dimensional array is array of arrays. Logically, we can think of multi dimensional array as table a with row and columns.

Loot at the below example, where we are creating a multi dimensional array with row 4 and column 6. So the structure will look similar to below.



See above, an array of size 6 will be created which will hold other arrays on each location with size of 4. So multi dimensional array is nothing but array of arrays.

Syntax of creating multi dimensional array in java

There are different ways of creating multi dimensional array in java, each of them are valid. Note*: you need to tell how many rows should be there, but you may or may not specify the number of columns.

int[][] a = new int[size][];
int a[][] = new int[size][size];
int [][]a = new int[size][];

Example of multi dimensional array

We will create a matrix of elements using multi dimensional array in java.

class ArrayDemo {

   public static void main(String arg[]) {

      int a[][] = new int[2][2]; // 2D array of 2x2 row x columns

      for(int i=0; i<2; i++) {
        for(int j=0; j<2; j++) {
           a[i][j] = (i + j);
        }
      }

      for(int i=0; i<2; i++) {
        for(int j=0; j<2; j++) {
           System.out.print(a[i][j] + " ");
        }
        System.out.println();
      }
 }
}
output :
0 1 
1 2

You can also use literals to initialize multi dimensional array as below :

class ArrayDemo {

   public static void main(String arg[]) {

      int a[][] = {
                     {1,3,5,6},
                     {4,2,6,1,4,2,3}
                  };

      for(int i=0; i<a.length; i++) {
        for(int j=0; j<a[i].length; j++) {
           System.out.print(a[i][j] + " ");
        }
        System.out.println();
      }
 }
}
output :
1 3 5 6 
4 2 6 1 4 2 3 

Note*: In the above example, the length of the row and columns could be different. We need a way to determine the length of row and column at run time. So we can use the below method for that.

a.lenght : Will give the size of the rows.
a[i].lenght : Will provide you the size of each array in columns.


You can play with array by implementing below programs. Please try to implement these programs on your own, do not take the help from google.

  1. Write a Java program to sum values of an array.
  2. Write a Java program to print the following grid.
  3. Write a Java program to calculate the average value of array elements.
  4. Write a Java program to test if an array contains a specific value.
  5. Write a Java program to find the index of an array element.
  6. Write a Java program to remove a specific element from an array.
  7. Write a Java program to copy an array by iterating the array.
  8. Write a Java program to insert an element (specific position) into an array.
  9. Write a Java program to find the maximum and minimum value of an array.
  10. Write a Java program to reverse an array of integer values.
  11. Write a Java program to find the duplicate values of an array of integer values.
  12. Write a Java program to find the common elements between two arrays, integer values.
  13. Write a Java program to find the second largest element in an array.
  14. Write a Java program to add two matrices of the same size.
  15. Write a Java program to test the equality of two arrays.

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *