TechiePassion is reader-supported. As an Amazon Associate I earn from qualifying purchases.

A Definitive Guide on Java Arrays in 2024

java-array

An array is a collection of elements with similar data types. Users can define string arrays, number arrays, and many other types of arrays. Each element in the array can be accessed through the index whose number starts from zero and the last index is one less than the number of elements.

For example, if there are five elements in an array, their indexes will be 0, 1,2, 3, 4. Here is the syntax of declaring an array variable.

SYNTAX 1

datatype [] arrayvar

SYNTAX 2

dataType arrayvar[]

The developers mostly prefer the first syntax.

Types of Arrays

There are three types of arrays in Java which are:

  1. One dimensional
  2. Multidimensional array
  3. Jagged array

1. One Dimensional Array

A one-dimensional array includes the elements of a single data type. It can be a string, integer, float, double, etc. While initializing arrays, users cannot insert the element that does not belong to the data type else they will get compile-time or runtime error.

Here is the syntax of declaring a one-dimensional array.

Int []b;

2. Multi-Dimensional Array

A multidimensional array consists of two or more arrays declared using a single variable. With this type of array, users also have the option of creating an array of arrays. Here is the syntax of defining multidimensional arrays.

Int [][]a;

In the same way, three or more dimensional arrays can be declared.

Int [][][]b;

3. Jagged Array

A jagged array is the array of arrays whose sizes are different. In this type of arrays, we can declare a variable number of columns.

Declaring Array Variables

Array variables are declared on the basis of the type of array a developer has to define. Here we will define single dimensional and multi-dimensional arrays.

The syntax of declaring one-dimensional arrays.

int []a;
String [] str;

The syntax of declaring multi-dimensional arrays.

int [][]a;
double [][][] b;

These arrays can be initialized according to the index or with loops.

Creating Arrays

The developers have to mention the number of elements for one-dimensional arrays and rows and columns in multidimensional arrays. Here we will see how to create arrays.

Int []a; 
a = new int[4];

In this code, we have declared four elements for the array variable a.

double [][]c;
c = new double[3][4];

In this code, we have created three rows and four columns.

Processing Arrays

The arrays can be processed easily but the developers have to be aware of exceptions related to arrays. Here are the examples which will show the method of creating, initializing, and getting the output from the arrays. We will both type of arrays in different examples.

Example of a One-Dimensional Array

class ArrayExample
{
public static void main(String []args)
{
Int []a;
a = new int[4];
a[0]=11;
a[1]=12;
a[2]=13;
a[3]=14;
System.out.println(a[3];
}
}
The output of the example is 14.
Here is another example of creating arrays
class ArrayExample2
public static void main(String []args)
{
Int []a = {11, 12, 13, 14};
System.out.println(a[3];
}
}

The OUTPUT will be 14.

Example of Multi-Dimensional Array

In this example, we will create a two-dimensional array and see the output.

class MultiArrayExample
{
public static void main(String []args)
{
int [][]a;
a = new int[3][4];
a[0][1] = 40;
System.out.println(a[0][1];
}
}

The OUTPUT of the code will be 40.

Foreach Loops

The foreach loop is used to extract data from each element of an array. The starting of the loop is that of a for loop. In this loop, a loop counter is not declared. Instead, a variable is declared whose data type is the same as an array. For example, if the array is of the int type, then the variable in the loop should also be of int type.

The SYNTAX of this loop is as follows –

for(int type var : array)
{
Statements
}

Its equivalent code in the for loop is as follows –

for(int i=0; i num)
{
num =
mynum;
}
return num;
}
}
}

Passing Arrays to Methods

Developers can pass the arrays in the same way as they pass the single variables. This technique is used to pass a large amount of data from one method to another.
Here is an example of passing an array as a parameter in a method.

public class PassArrayDemo
{
public static void myoutput(int y[])
{
System.out.println(y[0]);
y[0] = 100;
}
public static void main(String args[])
{
int x[] = { 10, 20, 30 };
System.out.println(x[0]);
myoutput(x);
System.out.println(x[0]);
}
}

Accessing Arrays Using For Loop

We have seen how the foreach loop can be used for retrieving elements from arrays. Now we will see the ways of retrieving data through for loop. Each element of the array can be accessed through the index of the element. The index of the first element is zero and the index of the last element is one less than the total number of elements. An example is shown in the table below.

Array Elements12345
Array Index01234

Here is a program of using for loop to access arrays.

class ForLoopArray
{
public static void main (String args[])
{
int a[] = new int[]{1, 2, 3, 4, 5};
for (i=0; I < a.length; i++)
{
System.out.println(a[i]);
}
}
}


OUTPUT -


1, 2 ,3, 4, 5

ArrayIndexOutofBounds Exception

Developers will get this error at runtime when they try to access an element of the index, which is not present in the array.

Here is an Example –

class ArrayException
{
public static void main (String args[])
{
int a[] = new int[]{1, 2, 3, 4, 5};
for (i=0; I <= a.length; i++)
{
System.out.println(a[i]);
}
}
}

It will show error at runtime as we are trying to access an element out of the array. In the loop we have written i <= a.length. It means that it will go to the sixth index, which is not available.

Cloning Arrays

Array is a subclass that inherits all the elements of Object class. The clone() method will help to copy the elements of one array to another.

Here is a program of cloning the array.

class ArrayCloning
{
public static void main (String args[])
{
int a[] = new int[]{1, 2, 3, 4, 5};
int aclone[] = a.clone();
for (i=0; I <= aclone.length; i++)
{
System.out.println(aclone[i]);
}
}
}


OUTPUT -


1, 2, 3, 4, 5

Inserting Elements Into an Already Existing Index

There is a situation when a developer needs to add some elements in the array. This can be done in the following program.

public class AddElements
{
public static void main (String []args)
{
int[] arr1 = new int(20);
int insind = 10;
int newvalue=20;
for (int i = arr1.length-1; i>insind; i--)
{
arr1[i] = arr1 [i-1];
}
arr1[insind] = newvalue;
System.out.println(Arrays.toString(arr1));
}
}

Removing Elements From Arrays

If a developer wants to remove an element from an array, he will have to remove an array index to do the needful; Here is an example of removing an element from an array.

public class RemoveElements
{
public static void main (String []args)
{
int[] arr1 = new int(20);
arr1[10] = 123;
int removeindex = 10;
for (int i = removeindex; i<iarr1.length; i++)
{
arr1[i] = arr1 [i+1];
}
System.out.println(Arrays.toString(arr1));
}
}

Finding Minimum and Maximum Values

The arrays contain many elements and if a developer wants to find minimum and  maximum values, he can do so through the following program.

public class MinMaxVal
{
public static void main(String []args)
{
int []arr1 = new int {4, 1,3, 7, 9};
int minVal = Integer.MAX_VALUE;
for (i=0; I < arr.length; i++)
{
if(arr1[i] < minVal )
{
minval = arr1[i];
}
}
System.out.println(minVal);
}
}

Arrays Class

Arrays class is present in java.util package. Developers can use this class to perform various operations on arrays. We will see this through the following examples.

Copying One Array Into Another

import java.util.*;
public class CopyArray
{
public static void main(String[] args)
{
int []arr1 = new int[10];
int []arr2 = new int[10];
for(i=0; i<arr1.length; i++)
{
arr1[i]=i;
}
for(i=0; i<arr1.length; i++)
{
arr2[i]=arr1[i];
}
}
}

There are many other methods of Arrays class, which the users can use to add, insert, delete, compare  and do other operations on arrays.

Conclusion

Arrays help to define many elements in comparison to a single variable and developers can use them to insert and retrieves a long range of data. The developers can also use Arrays class available in the java.util package to do various types of operations on arrays. Besides advantages, there are some disadvantages also like having knowledge of a number of elements in an array, memory allocation, time consumption in inserting and dieting elements etc.

In spite of this, developers should use arrays as they can store multiple values, and users need not define single values for each variable and remember them. This is the main advantage of arrays over single variables. Apart from Arrays there are a lot of data structures that can be used in Java. Some of them are Queues, Stacks and Linked Lists.