Arrays in Java are complex data structures designed to hold numerous elements of a uniform data type within a unified memory space. The upcoming section will delve into the realm of Java arrays, exploring their classifications, characteristics, and practical implementation in software applications.
What is an Array?
An array is a grouping of elements with a common data type that are stored in a consecutive memory block. Arrays enable the organization of related data items and provide a means to retrieve them by specifying an index.
Array in Java
In the Java programming language, an array is a data structure that holds elements of the same data type in consecutive memory locations within an object. Arrays are utilized to store a specific quantity of elements.
In Java, arrays are structured based on indices, where the initial element is located at index 0, the subsequent element at index 1, and following the same pattern for the rest of the elements.
In Java, arrays are viewed as instances of a class that is created dynamically. In Java, all arrays should:
- Implement the Serializable and Cloneable interfaces
- Inherit from the Object class
Arrays in Java are capable of holding primitive values or objects. Java facilitates the use of both one-dimensional and multi-dimensional arrays.
Java also provides the functionality of anonymous arrays, a feature absent in C/C++. This capability enables the creation and passing of arrays without the need to explicitly declare a variable.
There are two categories of arrays: single-dimensional and multi-dimensional arrays.
Single-Dimensional Array in Java
In Java, a one-dimensional array is a sequential grouping of elements that share a common data type. It can be defined and created using the syntax provided below.
Syntax of Declaring an Array
The following is the format for defining a one-dimensional array in Java:
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Syntax of Instantiation of an Array
The following is the syntax for creating a one-dimensional array in Java:
arrayRefVar=new datatype[size];
Example of Single Dimensional Array
Let's examine a straightforward illustration of a Java array. In this example, we will demonstrate how to declare, create an instance of, initialize, and traverse an array.
Source Code
public class Main{
public static void main(String args[]){
//declaration and instantiation of an array
int a[]=new int[5];
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]);
}
}
}
Output:
10
20
70
40
50
Multidimensional Array (Two-Dimensional Array)
In Java, a multidimensional array, specifically a two-dimensional array, comprises arrays within an array, where each element in the primary array is an array. This type of array is employed to organize data in a tabular format resembling rows and columns.
Syntax of Declaring a Two-Dimensional Array
The following is the syntax used to define a two-dimensional array in the Java programming language:
dataType[][] arrayName;
Syntax of Instantiation of a Two-Dimensional Array
The following is the syntax for creating a two-dimensional array in Java:
arrayName = new dataType[rows][columns];
or you can combine declaration and instantiation:
dataType[][] arrayName = new dataType[rows][columns];
Example of Two-Dimensional Array
Let's explore a basic illustration of a two-dimensional array in Java, demonstrating the declaration, instantiation, initialization, and traversal of the array:
public class Main {
public static void main(String[] args) {
// Declare and instantiate a 2D array
int[][] numbers = new int[2][3];
// Initialize the array
numbers[0][0] = 10;
numbers[0][1] = 20;
numbers[0][2] = 30;
numbers[1][0] = 40;
numbers[1][1] = 50;
numbers[1][2] = 60;
// Traverse and print the array
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers[i].length; j++) {
System.out.print(numbers[i][j] + " ");
}
System.out.println();
}
}
}
Output:
10 20 30
40 50 60
Accessing Array Elements Using For Each Loop
Array elements can be accessed using a for-each loop in Java. This type of loop iterates through the elements of the array individually, assigning each element to a variable before executing the loop body.
Syntax
The syntax of the for-each loop is given below:
for(data_type variable:array){
//body of the loop
}
Let's explore an example demonstrating how to print the elements of a Java array by utilizing the for-each loop.
Example
//Java Program to print the array elements using for-each loop
public class Main{
public static void main(String args[]){
//declaration and initialization of an array
int arr[]={33,3,4,5};
//traversal of an array using for-each loop
for(int i:arr)
System.out.println(i);
}
}
Output:
33
3
4
5
Passing Array to a Method
By passing a Java array to a method, we enable the reusability of the logic on various arrays. In Java, when an array is passed to a method, a reference to the array is essentially passed. This implies that the method can access the array data just like the calling code, and any changes made to the array within the method will impact the original array.
Let's explore a basic example demonstrating how to retrieve the smallest number from an array by utilizing a method.
Example
//Java Program to demonstrate the way of passing an array to method.
public class Main{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}
}
Output:
Explanation
This Java program illustrates the process of passing an array to a function. The findMin function accepts an integer array named arr as an argument and determines the smallest element in the array by utilizing a basic iterative loop. Within the primary function, an integer array named a is defined and set with the values {33, 3, 4, 5}. Subsequently, the findMin function is invoked with this array passed as a parameter. The findMin function traverses the array to identify the smallest element and displays it on the console.
Anonymous Array
Anonymous arrays in Java offer a convenient way to create and initialize arrays directly within method calls or expressions, removing the need for separate array variable declarations. This feature is particularly useful when dealing with temporary arrays required for a specific task without the need for a lasting reference in the program.
In Java, anonymous arrays are supported, which eliminates the need to explicitly declare an array when passing it to a method.
Example
//Java Program to demonstrate the way of passing an anonymous array to method
public class Main{
//creating a method which receives an array as a parameter
static void printArray(int arr[]){
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
public static void main(String args[]){
printArray(new int[]{10,22,44,66});//passing anonymous array to method
}
}
Output:
10
22
44
66
Explanation
The given illustration showcases the utilization of an array print method that accepts an integer array as its input and displays every element within the array. Within the primary function, a nameless array {10, 20, 30} is promptly provided as an input to the printArray function. This succinct approach highlights the application of anonymous arrays in Java, enabling a more efficient code structure without necessitating interim variable assignments.
Returning Array from the Method
In Java, methods are not restricted to returning basic data types or objects; they also have the capability to return arrays. This functionality provides increased versatility in method structuring and empowers developers to encapsulate intricate processes for array generation within methods.
Example
//Java Program to return an array from the method
public class Main{
//creating method which returns an array
static int[] get(){
return new int[]{10,30,50,90,60};
}
public static void main(String args[]){
//calling method which returns an array
int arr[]=get();
//printing the values of an array
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
}
Output:
10
30
50
90
60
Explanation
The illustration showcases the process of retrieving an array from a Java method and then applying the obtained array in the calling code. By containing the creation and setup of the array within the get method, the code gains modularity and reusability.
ArrayIndexOutOfBoundsException
Within the Java programming language, the ArrayIndexOutOfBoundsException is an exception that occurs at runtime. The Java Virtual Machine (JVM) triggers this exception when an attempt is made to access an index of an array that is not valid. This exception arises in situations where the index is either negative, matches the array's size, or exceeds the array's size when navigating through the array.
Example
An illustration is provided below to showcase how an ArrayIndexOutOfBoundsException can occur in a Java array:
//Java Program to demonstrate the case of
//ArrayIndexOutOfBoundsException in a Java Array.
public class TestArrayException{
public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++){
System.out.println(arr[i]);
}
}}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at TestArrayException.main(TestArrayException.java:5)
50
60
70
80
Jagged Arrays
In the Java programming language, a jagged array refers to an array structure consisting of arrays, where each array may contain a varying number of elements. This is in contrast to a standard two-dimensional array, where every row possesses an equal number of elements.
Declaring and Initializing a Jagged Array
In Java, when declaring a jagged array, you start by declaring an array that contains arrays. Each array within this structure represents a row, and you need to initialize each row individually with its own set of columns.
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
Example
An illustration below showcases how a jagged array can be utilized in Java:
Example
//Java Program to illustrate the jagged array
public class Main{
public static void main(String[] args){
//declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
//printing the data of a jagged array
for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
}
}
}
Output:
0 1 2
3 4 5 6
7 8
Explanation
This Java code showcases the concept of a jagged array, which involves creating an array of arrays where each inner array has a different column count. Initially, a 2D array called "arr" is defined with 3 rows. However, each row varies in the number of columns: the first row contains 3 columns, the second one has 4 columns, and the third row consists of 2 columns. The program proceeds to populate the jagged array by assigning sequential values starting from 0. Subsequently, it traverses through the array and displays each element in a row-by-row fashion, separated by spaces, while marking the end of each row with a newline character.
Arrays as Objects
In Java, an array is considered an object, but it has a unique characteristic where a proxy class is created by the JVM for every array object. This proxy class reflects the array's runtime type. To retrieve the class name of a Java array, you can utilize the getClass.getName function, which is accessible for all Java objects. This function provides a String that displays the complete name of the object's class, inclusive of any package details.
Example
In the illustration below, we demonstrate how to retrieve the class name of an array during runtime in Java by utilizing the method getName from getClass.
Example
//Java Program to get the class name of array in Java
public class Main{
public static void main(String args[]){
//declaration and initialization of array
int arr[]={4,4,5};
//getting the class name of Java array
Class c=arr.getClass();
String name=c.getName();
//printing the class name of Java array
System.out.println(name);
}
}
Output:
Explanation
In this Java example, the process of obtaining the class name of an array in Java is illustrated through the utilization of the getClass.getName method. A new array named arr is created, containing integer values. The program then acquires the runtime class of the array by employing getClass, and subsequently retrieves the class name with the aid of getName. The resulting class name, commonly denoted by a solitary character succeeded by square brackets, accurately signifies both the dimensionality and element type within the array.
Copying Arrays
To duplicate an array in Java, you can utilize the arraycopy function from the System class. It enables the replication of elements from one array to another by specifying the starting index and the number of elements to be copied.
Syntax of arraycopy method
Below is the syntax of arraycopy method:
public static void arraycopy(
Object src, int srcPos,Object dest, int destPos, int length
)
In this scenario, the array to copy from is referred to as src, with srcPos indicating the initial position within this array. On the other hand, dest represents the array to copy to, destPos specifies the starting point within the destination array, and the variable length denotes the quantity of elements to be duplicated.
Example
An illustration is provided below to showcase the process of transferring elements from one array to another in Java by utilizing the System.arraycopy method.
Example
//Java Program to copy a source array into a destination array in Java
public class Main {
public static void main(String[] args) {
//declaring a source array
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
//declaring a destination array
char[] copyTo = new char[7];
//copying array using System.arraycopy() method
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
//printing the destination array
System.out.println(String.valueOf(copyTo));
}
}
Output:
caffein
Explanation
A Java program is set up to create and populate two char arrays, named sourceArr and targetArr, with predetermined characters. The program proceeds to employ the System.arraycopy function to transfer a specified segment from the sourceArr array to the targetArr array. This operation begins at index 2 of the sourceArr array and copies a total of 7 elements. Upon completion, the program displays the elements stored in the targetArr array, which yields the displayed text "caffein".
Cloning an Array
Java supports the creation of array clones through the implementation of the Cloneable interface. When a clone of a one-dimensional array is made, it results in a deep copy, effectively duplicating the actual values within the Java array. However, when a clone of a multidimensional array is created, it leads to a shallow copy, copying only the references within the Java array.
This differentiation is significant as changes made to elements in a shallow duplicated multidimensional array will impact both the initial array and its clone. Conversely, in a deep-copied one-dimensional array, alterations will not influence the original array.
Example
Below is an example showcasing the closing of an array in Java:
//Java Program to clone the array
class TestarrayClone{
public static void main(String args[]){
int arr[]={33,3,4,5};
System.out.println("Printing original array:");
for(int i:arr)
System.out.println(i);
System.out.println("Printing clone of the array:");
int carr[]=arr.clone();
for(int i:carr)
System.out.println(i);
System.out.println("Are both equal?");
System.out.println(arr==carr);
}
}
Output:
Printing original array:
33
3
4
5
Printing clone of the array:
33
3
4
5
Are both equal?
False
Explanation
In this Java code snippet, we start by creating an array of integers named "originalArray" containing the values {33, 3, 4, 5}. We then display the elements of this array. Subsequently, the clone method is employed to create a copy of the original array, which is then assigned to a new array named "copiedArray". The contents of the copied array are then printed to the console. Finally, a comparison is made between the original array and the copied array using the == operator, resulting in a boolean value of false, indicating that they are separate array instances. It is important to note that the elements within both arrays are identical.
Addition Two Multidimensional Arrays (Two Matrices)
Matrix addition is a key operation in linear algebra and computer science, commonly applied in diverse fields like scientific computation, digital design, and visual data manipulation. In Java, when combining two matrices, elements at corresponding positions are summed to generate a new matrix with identical dimensions as the original. The following Java code demonstrates a straightforward approach to matrix addition by employing nested loops to perform a simple illustration of the procedure.
Example
Let's consider a basic illustration demonstrating the addition of two matrices.
//Java Program to demonstrate the addition of two matrices in Java
class ArrayAddition{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}}
Output:
2 6 8
6 8 10
Explanation
The following Java code showcases the addition of two predefined matrices, a and b, by adding their elements together and saving the result in matrix c. Matrices a and b are preloaded with values, while matrix c is initialized to hold the sum. The program iterates through each element of the matrices using nested loops, adding the respective elements from matrices a and b, and storing the outcome in the corresponding position in matrix c. Upon completion, the program outputs the resultant matrix c, illustrating the element-wise addition of the two matrices where each element in matrix c represents the sum of the corresponding elements in matrices a and b.
Multiplication Two Multidimensional Arrays (Two Matrices)
Performing matrix multiplication is an essential mathematical and computer science procedure that finds applications in fields like graphics rendering, optimization algorithms, and scientific computing. In Java, the multiplication of two matrices follows a structured approach wherein each element in the resultant matrix is determined by calculating the dot product of a row from the initial matrix and a column from the second matrix.
Example
The upcoming demonstration illustrates the process of multiplying two matrices:
//Java Program to multiply two matrices
public class MatrixMultiplicationExample{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
//creating another matrix to store the multiplication of two matrices
int c[][]=new int[3][3]; //3 rows and 3 columns
//multiplying and printing multiplication of 2 matrices
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}}
Output:
6 6 6
12 12 12
18 18 18
Explanation
The following Java code calculates the product of two 3x3 matrices, denoted as 'a' and 'b', and saves the outcome in matrix 'c'. It starts by setting up matrices 'a' and 'b' with predetermined values and then creates matrix 'c' to hold the final result. By employing nested loops, the program traverses through each element of matrix 'c', computing the dot product of the matching row and column elements from matrices 'a' and 'b'. The program adds up the calculated value for each element into the respective position in matrix 'c'.
Arrays Programs
Listed below are some significant Java programs related to arrays: