Arrays in Java

Programming languages or concepts
0

Arrays in Java



In this tutorial, we will learn about arrays in java and how it work in Java. We will learn initialize array in java, how to initialize array in java, how to declare an array in java, declare array in java, array declaration in java ,how to declare array in java, how to create an array in java, how to print array in java and access array elements with the help of examples.

 In this article, we will discuss arrays in data structures. Arrays are defined as a collection of similar data items stored on attached memory locations. It is one of the simplest data structures that can be accessed randomly using the index number of each data element. 

An array is a collection of elements stored at contiguous memory locations. The idea is to put together several items of the same type. This makes it easier to calculate the position of each component by simply adding an offset to the base value, i.e. the memory position of the first component of the array. The base value index is 0 and the difference between the two indices is offset.

Java Arrays

An arrays is a collection of same types of elements.

An arrays is used to store multiple values ​​in a single variable instead of declaring separate variables for each value.

Normally, an java arrays is a collection of similar elements to which memory space is attached / contiguous memory location.

A Java array is an object that contains elements of the same data type. It is a data structure where we store the same elements. We can only keep a fixed set of elements in a Java array.

Java arrays is a index-based, in java array the first element stored on the 0th index, the 2nd element is stored on the 1st index and so on

Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the sizeof operator.

An array in Java is a set of identical-typed variables referred to by a common name. Arrays in Java work differently than they do in C/C++. Following are some important points about Java arrays. 

 

In Java, all arrays are dynamically allocated.

Since an array is an object in Java, we can find their length using the object property length. This is different from C/C++, where we find length using sizeof.

Java array variables can also be declared as other variables with [] after the data type.

The variables in the array are sorted and the index of each starts from 0.

Java arrays can also be used as static fields, local variables or method parameters.

The size of the array should be specified by int or short value and should not be long.

An array type is a direct superclass object.

Each array type applies Cloneable and java.io.Serializable interfaces.

 

An array can have primitive (int, four, etc.) and object (or non-primitive) references to the class according to the definition of an array. In the case of primitive data types, the actual values ​​are stored in the attached memory locations. In the case of class objects, the actual objects are stored in the heap segment.

 

 

For example, if we want to store the names of 1000 peoples then we can create an array of the string type that can store 1000 names.

 

String[] arr = new String[1000];

 

We have now declared a variable ( arr ) that holds an array of strings types. To insert values to the variable, we can use an array literal - place the values in a comma - separated list, inside curly braces as showing in following examples

 

String[] languages = {"C", "Cpp", "Java", "python"};

To create an array of integers, you could write:

 

int[] num = {97, 98, 100, 99};

 

Access the Elements of an Array

we can access an array elements by using referring to the index number.

 

This statement accesses the value of the first element in programming languages:

 

Example

String[] languages = {"C", "Cpp", "Java", "python"};

System.out.println(languages[2]);

 

outpout:

                Java

 

 

Change an Array Element

To change the value of a especial element, with refer to the index number:

 

Example

 languages[0] = "C#";

Example

String[] languages = {"C", "Cpp", "Java", "python"};

languages[0] = "C#";

System.out.println( languages[0] );

 

array declaration in java

In Java, here is how we can declare an array.

declare array in java

dataType[] arrayName;

dataType - it can be primitive data types like int, char, double, byte, etc. or Java objects

arrayName - it is an identifier

For example,

 

int[] rollNumber;

 

how to declare an array in java? 

array declaration in java ?

how to declare array in java ?

declare array in java  ?

 

how to initialize array in java 

In Java, we can also initialize arrays during declaration. 

For example,

initialize array in java

//declare and initialize and array at same time

int[] numbers = {2, 4, 6, 8, 10};

Now, we have created an array named as numbers and initialized it with the values inside the curly brackets and the values are Separate using commas.

 

 

How to Access Elements of an Array in Java? , how to print array in java

We can access the elements of an array using the index numbers. 

below is the syntax for accessing elements of an array,

 

// access array elements

array[index]

Let's see an example of accessing array elements using index numbers.

 

Example: Access Array Elements

class Main {

 public static void main(String[] args) {

  

   // create an array

   int[] numbers = {2, 4, 6, 8, 10};

 

   // access each array elements

   System.out.println("Accessing Elements of Array:");

   System.out.println("First Element: " + numbers[0]);

   System.out.println("Second Element: " + numbers[1]);

   System.out.println("Third Element: " + numbers[2]);

   System.out.println("Fourth Element: " + numbers[3]);

   System.out.println("Fifth Element: " + numbers[4]);

 }

}

 

 

Looping Through Array Elements

In Java, we can also loop through each element of the array. For example,

 

Example: Using For Loop

class Main {

 public static void main(String[] args) {

  

   // create an array

   int[] numbers = {2, 4, 6,8,10};

 

   // loop through the array

   // using for loop

   System.out.println("Using for Loop:");

   for(int i = 0; i < numbers.length; i++) {

     System.out.println(numbers[i]);

   }

 }

}

 

 

Multidimensional Arrays / two dimensional array in java

Arrays we have mentioned till now are called one-dimensional arrays. However, we can declare multidimensional arrays in Java.

 

A multidimensional array is an array of arrays. That is, each element of a multidimensional array is an array itself. For example,

 

double[][] matrix = {{1.2, 4.3, 4.0}, 

      {4.1, -1.1}

};

 

 

Advantages

Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.

Random access: We can get any data located at an index position.

Disadvantages

Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in Java which grows automatically.

 

 

Types of Array in java

There are two types of array.

list to array in java

Single Dimensional Array
Multidimensional Array
Single Dimensional Array in Java
Syntax to Declare an Array in Java

 

dataType[] arr; (or)  

dataType []arr; (or)  

dataType arr[];  

Instantiation of an Array in Java

 

arrayRefVar=new datatype[size];  

Example of Java Array

Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an array.

 

//Java Program to illustrate how to declare, instantiate, initialize  

//and traverse the Java array.  

class Testarray{  

public static void main(String args[]){  

int a[]=new int[5];//declaration and instantiation  

a[0]=10;//initialization  

a[1]=20;  

a[2]=70;  

a[3]=40;  

a[4]=50;  

//traversing array  

for(int i=0;i<a.length;i++)//length is the property of array  

System.out.println(a[i]);  

}

}  

 

 

Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:

 

int a[]={33,3,4,5};//declaration, instantiation and initialization  

Let's see the simple example to print this array.

 

 

class Testarray1{  

public static void main(String args[])

    {  

        int a[]={33,3,4,5};//declaration, instantiation and initialization  

        //printing array  

        for(int i=0;i<a.length;i++)//length is the property of array  

        System.out.println(a[i]);  

    }

}  

 

 

Multidimensional Array in Java

In such case, data is stored in row and column based index (also known as matrix form).

 

Syntax to Declare Multidimensional Array in Java

 

dataType[][] arrayRefVar; (or)  

dataType [][]arrayRefVar; (or)  

dataType arrayRefVar[][]; (or)  

dataType []arrayRefVar[];   

Example to instantiate Multidimensional Array in Java

 

int[][] arr=new int[3][3];//3 row and 3 column  

Example to initialize Multidimensional Array in Java

 

arr[0][0]=1;  

arr[0][1]=2;  

arr[0][2]=3;  

arr[1][0]=4;  

arr[1][1]=5;  

arr[1][2]=6;  

arr[2][0]=7;  

arr[2][1]=8;  

arr[2][2]=9;  

Example of Multidimensional Java Arrays

Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

 

 

class Testarray3{  

        public static void main(String args[])

        {  

                //declaring and initializing 2D array  

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

                //printing 2D array  

                   for(int i=0;i<3;i++)

                    {  

                             for(int j=0;j<3;j++)

                               {  

                                       System.out.print(arr[i][j]+" ");  

                                }  

                                System.out.println();  

                    }  

          }

}  

  

Types of indexing in an array : 

·         0 (zero-based indexing): The first element of the array is indexed by a subscript of 0.

·         1 (one-based index): The first element of an array is indexed by a subscript of 1.

·         n (n-based index): The base index of the array can be selected freely. Typically, programming languages ​​allow n-based indexing. Negative index values ​​and other scalar data types such as calculations, or characters can be used as array indexes.

 

Properties of array

Some of the properties of the array are listed below-

  • Each element in an array is of the same data type and carries the same size that is 4 bytes.
  • Elements in the array are stored at contiguous memory locations from which the first element is stored at the smallest memory location.
  • The elements of the array can be accessed at random because you can calculate the address of each element of the array and the size of the data element with the given base address.

Representation of an array

We can represent arrays in different ways in different programming languages. For example, let us see the declaration of an array in C language -

 

As per the example above, some of the following are important points -

  • Index starts with 0.
  • The array's length is 10, which means we can store 10 elements.
  • Each element in the array can be accessed via its index.

Why are arrays required?

Arrays are useful because -

  • Value arrays are easy to find and find in arrays. 
  • Arrays are best for quick and easy processing of multiple values.


Arrays are good for storing multiple values in a single variable - In computer programming, most cases require storing a large number of data of a similar type. To store this amount of data, we need to define a large number of variables. It will be very difficult to remember the names of all the variables when writing programs. Instead of naming all the variables separately, it is better to define an array and store all the elements in it.

Memory allocation of an array

As mentioned above, all the data components of the array are stored in the attached space in the main memory. The name of the array represents the base address or the address of the first element in the main memory. Each element of the array is represented by the appropriate index.

We can define the indexing of an array as follows -

  1. 0 (zero-based index): The first element of the array will be arr [0].
  2. 1 (one-based indexing): The first element of the array will be arr[1].
  3. n (n - based indexing): The first element of the array can reside at any random index number.

 

In the image above, we have shown the memory allocation of an array of 5 sizes.The array follows a 0-based indexing approach. The base address of the array is 100 bytes. It is the address of arr[0]. Here, the size of the data type used is 4 bytes; therefore, each element will take 4 bytes in the memory.

How to access an element from the array?

We need the information below to access any random element in the array -

  • Base Address of the array.
  • Size of an element in bytes.
  • Type of indexing, array follows.

The formula to calculate the address to access an array element -

Byte address of element A[i]  = base address + size * ( i - first index)  

 

Basic operations

Now, let's discuss the basic operations supported in the array -

  • Traversal :-

                             This operation is used to print the elements of the array.

  • Insertion :-

                              It is used to add an element at a particular index.

  • Deletion :-

                              It is used to delete an element from a particular index.

  • Search :-

                             It is used to search an element using the given index or by the value.

  • Update :-

                             It updates an element at a particular index.

 

Traversal operation

This operation is performed to traverse through the array elements. It prints all array elements one after another. We can understand it with the below program -

  

#include <stdio.h>  

void main() {  

   int Arr[5] = {18, 30, 15, 70, 12};  

int i;  

   printf("Elements of the array are:\n");  

   for(i = 0; i<5; i++) {  

      printf("Arr[%d] = %d,  ", i, Arr[i]);  

   }  

}  

 

Insertion operation

This operation is performed to insert one or more elements into the array. As per the requirements, an element can be added at the beginning, end, or at any index of the array. Now, let's see the implementation of inserting an element into the array.

 

#include <stdio.h>  

int main()  

{  

    int arr[20] = { 18, 30, 15, 70, 12 };  

    int i, x, pos, n = 5;  

    printf("Array elements before insertion\n");  

    for (i = 0; i < n; i++)  

        printf("%d ", arr[i]);  

    printf("\n");  

  

    x = 50; // element to be inserted  

    pos = 4;  

    n++;  

  

    for (i = n-1; i >= pos; i--)  

        arr[i] = arr[i - 1];  

    arr[pos - 1] = x;  

    printf("Array elements after insertion\n");  

    for (i = 0; i < n; i++)  

        printf("%d ", arr[i]);  

    printf("\n");  

    return 0;  

}  

 

Deletion operation

As the name implies, this operation removes an element from the array and then reorganizes all of the array elements.

 

#include <stdio.h>  

  

void main() {  

   int arr[] = {18, 30, 15, 70, 12};  

   int k = 30, n = 5;  

   int i, j;  

     

   printf("Given array elements are :\n");  

      

   for(i = 0; i<n; i++) {  

      printf("arr[%d] = %d,  ", i, arr[i]);  

   }  

      

   j = k;  

      

   while( j < n) {  

      arr[j-1] = arr[j];  

      j = j + 1;  

   }  

      

   n = n -1;  

     

   printf("\nElements of array after deletion:\n");  

      

   for(i = 0; i<n; i++) {  

      printf("arr[%d] = %d,  ", i, arr[i]);  

   }  

}  

 

Search operation

This operation is performed to search an element in the array based on the value or index.

 

#include <stdio.h>  

  

void main() {  

   int arr[5] = {18, 30, 15, 70, 12};  

   int item = 70, i, j=0 ;  

     

   printf("Given array elements are :\n");  

      

   for(i = 0; i<5; i++) {  

      printf("arr[%d] = %d,  ", i, arr[i]);  

   }  

    printf("\nElement to be searched = %d", item);  

   while( j < 5){  

      if( arr[j] == item ) {  

         break;  

      }  

          

      j = j + 1;  

   }  

      

   printf("\nElement %d is found at %d position", item, j+1);  

}  

 

Update operation

This operation is performed to update an existing array element located at the given index.

#include <stdio.h>  

  

void main() {  

   int arr[5] = {18, 30, 15, 70, 12};  

   int item = 50, i, pos = 3;  

     

   printf("Given array elements are :\n");  

      

   for(i = 0; i<5; i++) {  

      printf("arr[%d] = %d,  ", i, arr[i]);  

   }  

      

arr[pos-1] = item;    

   printf("\nArray elements after updation :\n");  

      

   for(i = 0; i<5; i++) {  

      printf("arr[%d] = %d,  ", i, arr[i]);  

   }  

}  

 

Complexity of Array operations

Time and space complexity of various array operations are described in the following table.

Time Complexity

Operation

Average Case

Worst Case

Access

O(1)  

O(1)

Search

O(n)

O(n)

Insertion

O(n)

O(n)

Deletion

O(n)

O(n)

 


In array, space complexity for worst case is O(n).Space Complexity

 

Applications on Arrays

·         Array stores data elements of the same data type.

·         Used in solving matrices problem

·         Applied as lookup table in computer.

·         Databases record are also implemented by array.

·         Helps in implementing sorting algorithm.

·         Different variable of same type can be saved under one name.

·         Arrays can be used for CPU scheduling.

·         Used to Implement other data structures like Stacks, Queues, Heaps, Hash tables, etc.

Advantages of Arrays

  • Array provides the single name for the group of variables of the same type. Therefore, it is easy to remember the name of all the elements of an array.
  • Traversing an array is a very simple process; we just need to increment the base address of the array in order to visit each element one by one.
  • Any element in the array can be directly accessed by using the index.

Disadvantages of Arrays

  • Array is homogenous. It means that the elements with similar data type can be stored in it.
  • In array, there is static memory allocation that is size of an array cannot be altered.
  • There will be wastage of memory if we store less number of elements than the declared size.


Tags:

Post a Comment

0Comments

Post a Comment (0)
close