Everything You Need to Know About “Arrays in Java”

array in java

Many of you already know about JAVA. Java is a programming language that follows object oriented concepts and is considered as a pure object oriented language. It follows every concept of object oriented programming. It is one of the popular languages and is used a lot to develop games. And the most interesting part of it is that it is platform independent and can be used on any operating system. Java focuses on many Object oriented concepts, however, an array is considered among the most important and oldest data structures and is used in almost every program. Which makes it more important to learn. To know more about arrays in java, implementations and different concepts used in arrays are all given in this article further. To know more follow the entire article.

What is a Java array?

Array in java is an object which contains a sequence of homogeneous elements that are all the elements with the same data type. These elements of the array are stored in a contiguous memory location and can have only a finite set of elements in the java array. All arrays in java are dynamically allocated.

It is index based and the first element of the array is stored at the 0th position and the rest of the elements follow the order. Java has a feature that inherits the object class and implements the serializable(i.e. It will convert an object or data structure into a format that can be stored) as well as a cloneable interface.

Array becomes an essential feature as they can store objects which makes the experience of working in Java much easier for programmers.

Types of array

Arrays in Java can be classified into 2 main types:

  • Single dimensional array
  • Multidimensional array

However, types of arrays can also consist of indexed arrays, multidimensional arrays, and associative arrays. But the basic classification of arrays is done as single and multiple dimensional as mentioned above.

Single dimensional array in Java

Single dimensional array can be said to be a type of linear array. When needed to access its elements, just a single subscript is used where one represents a row and the other represents a column index.

Declaring

A single dimensional array can be declared as

  1. Declaring one dimensional array and store values directly at a time

 Syntax : int number[ ] = { 1,2,3,4,5 };

The pair of square braces [ ] after an array name represents one dimension.

  • Declaring one dimensional array first and then allocating memory for it

Syntax : int number[ ];

   number = new int [5];

Initialising

The keyword “new” can be used to intialise an array, followed by the data type of the array

Syntax : int number[ ] = new int[5];

Or, you can also initialise an array with a non-default value

Syntax : int[] intArray = new int[10];

   intArray[0] = 22;

Accessing

Array can be accessed with the help of index.

Syntax : intArray[0] = 3;

   Int lastInt = intArray[5];

You can see any of the numbers that you have stored lately. But remember that the total numbers you have stored will get reduced by 1 while accessing as the first element in an array is stored as 0.

Multidimensional array in Java

An array can be more than one dimensional a two dimensional array is a frequently used type in java. It forms a matrix type structure with rows and columns. But it doesn’t end here, there are more than two dimensional arrays in java. However, it gets a bit difficult to visualise. They are used to hold a large amount of data, which is considered a useful feature when comes to data analysis.

Declaring

Two-dimensional array:

Syntax : int[ ][ ] a = new int[3][4];

Three-dimensional array:

Syntax : string[ ][ ][ ] data = new string[3][5][6];

Initializing

Two-dimensional array:

Syntax : int[ ][ ] a = {{1,2,3},{4,5},{8},}; 

Three-dimensional array:

Syntax : int[ ][ ][ ] test = { { {1,3,8},{4,5,6} },{ {8,3},{2},{7,6} } };

Accessing

Two-dimensional array:

Syntax : intval = intArray[0][2];

Three-dimensional array:

Syntax : int[ ][ ][ ] test = { { {1,3,8},{4,5,6} },{ {8,3},{2},{7,6} } };

Accessing an array in multidimensional array is similar to that of initialising.

Basic operations performed on Array in Java

Traverse

It prints all the element in the array one by one.

public class Main {

    public static void main(String[ ] args) {

        Int[ ] intArr = {2, 3, 5, 7, 11, 13, 17, 19};

        System.out.println(“The array elements are “);

         (int i = 0; i < intArr.length; i++)

 {

            System.out.print(intArr[i] + ” “);

        }

    }

}

Insertion

It adds an elements in the array at the mentioned index.

public class Main{

public static void main(String[] args)

{

int n = 5, x = 10, flag = 1, loc = 0;

Scanner s = new Scanner(System.in);

int intArr[] = new int[n];

Scanner sc = new Scanner(System.in);

System.out.println(“Enter the array elements : “);

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

{

intArr[i] = sc.nextInt();

}

System.out.println(“Array elements before insertion : “);

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

{

System.out.print(intArr[i] + ” “);

}

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

{

if(intArr[i] == x)

{

flag =1;

loc = i;

Break;

}

Else

{

flag = 0;

}

}

if(flag == 1)

{

for(int i = loc+1; i < n; i++)

{

intArr[i-1] = intArr[i];

}

System.out.print(“\nArray elements after deleting:”);

for (int i = 0; i < n-2; i++)

{

System.out.print(intArr[i]+” “);

}

System.out.print(intArr[n-2]);

}

Else

{

System.out.println(“Element not found”);

}

}

}

Deletion

It deletes an element from array at any given index.

public class Main{

 public static void main(String[] args)

 {

int search_ele = 15;

  int n = 5, flag = 0;

 Scanner s = new Scanner(System.in);

 int intArr[] = new int[n];

  Scanner sc = new Scanner(System.in);

System.out.println(“Enter the array elements : “);

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

 {

  intArr[i] = sc.nextInt();

 }

System.out.println(“The Array elements are: “);

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

 {

  System.out.print(intArr[i] + ” “);

 }

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

 {

  if(intArr[i] == search_ele)

 {

  flag = 1;

 break;

}

 }

 if(flag == 1)

 {

  System.out.println(“\nElement Found”);

 }

 else

 {

  System.out.println(“\nElement not found”);

 }

 }

}

It helps in searching an element in an array according to the given index or value.

public class Main{

 public static void main(String[] args)

 {

 int search_ele = 15;

 int n = 5, flag = 0;

 Scanner s = new Scanner(System.in);

 int intArr[] = new int[n];

 Scanner sc = new Scanner(System.in);

 System.out.println(“Enter the array elements : “);

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

 {

 intArr[i] = sc.nextInt();

 }

 System.out.println(“The Array elements are: “);

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

 {

 System.out.print(intArr[i] + ” “);

 }

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

 {

 if(intArr[i] == search_ele)

 {

 flag = 1;

 break;

 }

 }

 if(flag == 1)

 {

 System.out.println(“\nElement Found”);

 }

 else

 {

 System.out.println(“\nElement not found”);

 }

 }

}

Update

It updates an element at a given index.

public class Main{

 public static void main(String[] args)

 {

 int search_ele = 15;

 int n = 5,x;

 Scanner s = new Scanner(System.in);

 int intArr[] = new int[n];

 Scanner sc = new Scanner(System.in);

 System.out.println(“\nEnter the array elements : “);

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

 {

 intArr[i] = sc.nextInt();

 }

 System.out.println(“\nThe Array elements are: “);

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

 {

 System.out.print(intArr[i] + ” “);

 }

 System.out.println(“\nEnter the new element : “);

 x = sc.nextInt();

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

 {

 if(intArr[i] == search_ele)

 {

 intArr[i] = x;

 break;

 }

 }

 System.out.println(“Array elements after updating: “);

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

 {

 System.out.println(intArr[i] + ” ” );

 }

 }

}

Copying array in Java

Copying arrays using Assignment Operator

Consider the given program as an example:

class Main {

    public static void main(String[ ] args) {

        int [] num = {2,3,4,5,6,7};

        int [] positiveNum = num;    // copying arrays

        for (int num: positiveNum) {

            System.out.print(number + “, “);

        }

    }

}

In the above example, we have used an assignment operator “=” to copy an array “num” to another array named “positiveNum”.

This is the simplest and easiest technique. However, there is a problem with this technique. If we try to change an element in one array, the corresponding elements in other arrays will also get changed.

When this happens we call it a shallow copy(i.e. Only fields of primitive datatype are copied while the object references are not copied). And to make a new array objects while copying the arrays we need a deep copy(i.e. Both fields of primitive datatype and object references are copied).

Using Looping Construct to Copy Arrays

Consider the given program as an example:

class Main {

    public static void main(String[ ] args) {

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

        int [ ] destination = new int[6];

        // iterate and copy elements from source to destination

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

            destination[i] = source[i];

        }

         // converting array to string

        System.out.println(Arrays.toString(destination));

    }

}

In the above example for loop is used to iterate elements of the array. In every iteration, the elements get copied from “source” array to “destination” array.

Copying Arrays using arraycopy() method

The system class in java contains a method named arraycopy() to copy arrays. This is considered a better approach than the above two. This method allows us to copy a certain portion of the “source” array and “destination” array.

  Syntax : arraycopy(Object src, int srcPos,Object dest, int destPos, int length)

here,

src : source array that you want to copy

srcPos : starting position of index in the source array

dest : destination array where elements will get copied from the source

destPos : starting position of index in destination array.

lenght : total number of elements that you want to copy

Cloning array in Java

Java gives a feature to clone a array. If we create a clone of single dimensions array, it will create a deep copy in java which means, this method will create the exact clone of the original array and will return the exact length of array. However,  it is not the same case as single dimensional array, in multidimensional array the clone method creates the shallow copy of the Java array which means it copies the references.

Syntax : data_type[ ] array_name = array_name(that you want to clone).clone();

Boxing and unboxing arrays in Java

Before beginning this topic in array, let me first tell you what is boxing and unboxing in java.

Boxing is a conversion that is done in java compiler between the primitive type and the object wrapper classes(a class that whose object already contains a primitive data type in it. In short we can wrap the “values” of primitive data type into a wrapper class object). And unboxing is the opposite of boxing.

Consider the following example for boxing:

class BoxingEg1

{  

  public static void main(String args[ ])

{  

        int a=50;  

//boxing syntax

        Integer a2=new Integer(a);  

        Integer a3=5;

        System.out.println(a2+” “+a3);  

 }   

}  

Consider the following example for unboxing :

class UnboxingEg1{  

  public static void main(String args[]){  

    Integer i=new Integer(50);  

        int a=i;        

        System.out.println(a);  

 }   

}  

Jagged Array in Java

Jagged array is a multidimensional array with different size. It can be said as array of array. Jagged array is also known as ragged array. Jagged array is used to makesthings easier when we need to store data using multidimension but with same variable name. It makes the the program execution smooth and fast.

Declaring jagged array in two dimensional array:

Syntax : int array[ ][ ] = new int[3][ ];

Initialising jagged array in java:

Syntax : int myarray[ ][ ] = new int[ ][ ]{

    new int[ ] { 1, 2, 3 };

    new int[ ] { 4, 5, 6, 7 };

    new int[ ] { 8, 9 };

};

Conclusion

This article covers all the main concepts of array in java. This article tells you the importance of array and why is it used. What are the different types of arrays in java and how are they used. How are arrays declared, initialised and accessed with some programming codes as examples.

Leave a Comment

Your email address will not be published.