Java Arrays

An array is typically a grouping of elements of the same kind that are stored in a single, contiguous block of memory.

Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on.

In contrast to C/C++, the length member allows us to obtain the array's length. We must utilise the sizeof operator in C/C++.

An object of a dynamically formed class is called an array in Java. Java arrays implement the Serializable and Cloneable interfaces and derive from the Object class. In Java, an array can hold objects or primitive values. Java allows us to create single- or multi-dimensional arrays, just like C/C++ does.

Additionally, C/C++ does not support the anonymous array functionality that Java does.

Java Arrays

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: Arrays have a fixed size and do not grow dynamically at runtime.

Types of Array in java

There are two types of array.

  • Single Dimensional Array
  • Multidimensional Array

Single-Dimensional Array in Java

A single-dimensional array in Java is a linear collection of elements of the same data type. It is declared and instantiated using the following syntax:

Instantiation of an Array in Java

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.

Output:

10
20
70
40
50

Declaration, Instantiation and Initialization of Java Array

In Java, you can declare, instantiate, and initialize an array in a single line, as demonstrated below:

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

Output:

33
3
4
5

For-each Loop for Java Array

We can also print the Java array using for-each loop. The Java for-each loop prints the array elements one by one. It holds an array element in a variable, then executes the body of the loop.

The syntax of the for-each loop is given below:

Let's see the example of printing the elements of the Java array using the for-each loop.

Testarray1.java

Output:

33
3
4
5

Passing Array to a Method in Java

We can pass the Java array to the method so that we can reuse the same logic on any array. When we pass an array to a method in Java, we are essentially passing a reference to the array. It means that the method will have access to the same array data as the calling code, and any modifications made to the array within the method will affect the original array.

Let's see the simple example to get the minimum number of an array using a method.

Testarray2.java

Output:

3

Explanation

This Java program demonstrates the concept of passing an array to a method. The min method takes an integer array arr as a parameter and finds the minimum element in the array using a simple iterative loop. In the main method, an integer array a is declared and initialized with values {33, 3, 4, 5}, and then the min method is called with this array as an argument. The min method iterates through the array to find the minimum element and prints it to the console.

Anonymous Array in Java

Java's anonymous arrays eliminate the requirement for separate declarations of array variables by enabling developers to build and initialize arrays directly within method calls or other expressions. When working with temporary arrays that are just needed for a single job and don't need a persistent reference within the program, this is quite helpful.

Java supports the feature of an anonymous array, so we do not need to declare the array while passing an array to the method.

TestAnonymousArray.java

Output:

10
22
44
66

Explanation

In this example, the printArray method takes an integer array as a parameter and prints each element of the array. In the main method, an anonymous array {10, 20, 30} is directly passed as an argument to the printArray method. This concise syntax demonstrates the usage of anonymous arrays in Java, allowing for more streamlined code without the need for intermediate variable declarations.

Returning Array from the Method

In Java, methods are not limited to returning simple data types or objects; they can also return arrays. This feature allows for more flexibility in method design and enables developers to encapsulate complex logic for generating arrays within methods.

TestReturnArray.java

Output:

10
30
50
90
60

Explanation

The example demonstrates how to return an array from a method in Java and subsequently use the returned array in the calling code. By encapsulating array creation and initialization logic within the get method, the code becomes more modular and reusable.

ArrayIndexOutOfBoundsException

In Java, the ArrayIndexOutOfBoundsException is a runtime exception thrown by the Java Virtual Machine (JVM) when attempting to access an invalid index of an array. This exception occurs if the index is negative, equal to the size of the array, or greater than the size of the array while traversing the array.

TestArrayException.java

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
	at TestArrayException.main(TestArrayException.java:5)
50
60
70
80

Multidimensional Array in Java

A multidimensional array in Java is an array of arrays where each element can be an array itself. It is useful for storing data in row and column format.

Syntax to Declare Multidimensional Array in Java

Example to instantiate Multidimensional Array in Java

Example to initialize Multidimensional Array in Java

Example of Multidimensional Java Array

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

TestMultiArray.java

Output:

1 2 3
4 5 6
7 8 9

Explanation

This Java program initializes and prints a 2D array, representing a 3x3 matrix. Initially, a 2D array named arr is declared and initialized with values using array initializer syntax. The array consists of three rows, each containing three columns. The program then iterates through each row and column of the array using nested loops. Within the loops, it prints the value of each element, separated by a space. After printing all the elements of a row, a newline character is printed to move to the next line. This process continues until all elements of the array are printed. As a result, the program outputs the 3x3 matrix with each element displayed in its respective row and column.

These examples demonstrate the declaration, instantiation, initialization, and traversal of both single-dimensional and multidimensional arrays in Java.

Jagged Arrays in Java

In Java, a jagged array is an array of arrays where each row of the array can have a different number of columns. This contrasts with a regular two-dimensional array, where each row has the same number of columns.

Declaring and Initializing a Jagged Array

To declare a jagged array in Java, you first declare the array of arrays, and then you initialize each row separately with its own array of columns.

TestJaggedArray.java

Output:

0 1 2 
3 4 5 6 
7 8 

Explanation

This Java program demonstrates the concept of a jagged array, where an array of arrays is created, with each inner array having a different number of columns. Initially, a 2D array named arr is declared with 3 rows, but with each row having a different number of columns: the first row has 3 columns, the second row has 4 columns, and the third row has 2 columns. The program then initializes the jagged array by filling it with sequential values starting from 0. Finally, it iterates through the array and prints out each element, row by row, separated by a space, with a newline character indicating the end of each row.

What is the class name of a Java array?

In Java, an array is an object. However, arrays have a special feature in Java where the JVM generates a proxy class for each array object. This proxy class represents the runtime type of the array. To obtain the class name of a Java array, you can use the getClass().getName() method, which is available on all Java objects. This method returns a String representing the fully qualified name of the class of the object, including any package information.

Testarray.java

Output:

I

Explanation

This Java program demonstrates how to retrieve the class name of an array in Java using the getClass().getName() method. It initializes an array arr with integer values, obtains the runtime class of the array using getClass(), and retrieves the class name using getName(). The obtained class name, typically represented by a single character followed by square brackets, reflects the dimensionality and type of elements in the array.

Copying a Java Array

Copying an array in Java can be achieved using the arraycopy() method of the System class. This method allows you to copy elements from a source array to a destination array with a specified starting position and length.

Syntax of arraycopy method

Here, src is the source array, srcPos is the starting position in the source array, dest is the destination array, destPos is the starting position in the destination array, and length is the number of elements to be copied.

TestArrayCopy.java

Output:

caffein

Explanation

The Java program initializes two character arrays, copyFrom and copyTo, with predefined values. It then utilizes the System.arraycopy() method to copy a portion of the copyFrom array into the copyTo array, starting from index 2 and copying 7 elements. Finally, it prints the contents of the copyTo array, resulting in the output "caffein".


Cloning an Array in Java

In Java, arrays implement the Cloneable interface, allowing us to create clones of arrays. If we create a clone of a single-dimensional array, it creates a deep copy of the Java array. It means it will copy the actual value. But, if we create the clone of a multidimensional array, it creates a shallow copy of the Java array, which means it copies the references.

This distinction is important because modifying elements in a shallow copied multidimensional array will affect both the original and cloned arrays, while in a deep copied single-dimensional array, modifications will not impact the original.

TestarrayClone.java

Output:

Printing original array:
33
3
4
5
Printing clone of the array:
33
3
4
5
Are both equal?
False

Explanation

An integer array called arr is initialised with the numbers {33, 3, 4, 5} in this Java programme, and its elements are printed. Then, it uses the clone() method to duplicate arr, assigns the result to carr, and prints the items of the duplicated array. The last line of the programme compares arr and carr using the == operator; the result evaluates to false, meaning that arr and carr are distinct array objects. The elements in both arrays, though, are the same.

Addition of Two Matrices in Java

A fundamental operation in linear algebra and computer science, matrix addition is frequently utilised in a variety of applications, including scientific computing, computer graphics, and image processing. To create a new matrix with the same dimensions as the original, matching elements from each matrix must be added when adding two matrices in Java. This Java program shows how to add matrices effectively by using stacked loops to do a basic example of the process.

Let's see a simple example that adds two matrices.

ArrayAddition.java

Output:

2 6 8
6 8 10

Explanation

This Java program demonstrates matrix addition by adding two predefined matrices, a and b, element-wise and storing the result in matrix c. The matrices a and b are initialized with values, and matrix c is created to store the sum. It iterates through each element of the matrices using nested loops, adding corresponding elements from a and b and storing the result in the corresponding position in c. Finally, it prints the resulting matrix c. The output displays the element-wise addition of the two matrices, with each element in the resulting matrix c being the sum of the corresponding elements in a and b.

Multiplication of Two Matrices in Java

Matrix multiplication is a crucial operation in mathematics and computer science, often utilized in various applications such as graphics rendering, optimization algorithms, and scientific computing. In Java, multiplying two matrices involves a systematic process where each element in the resulting matrix is computed by taking the dot product of a row from the first matrix and a column from the second matrix.

Matrix Multiplication in Java

Let's see a simple example to multiply two matrices of 3 rows and 3 columns.

MatrixMultiplicationExample.java

Output:

6 6 6 
12 12 12 
18 18 18 

Explanation

This Java program computes the multiplication of two 3x3 matrices, 'a' and 'b', storing the result in matrix 'c'. It initializes matrices 'a' and 'b' with predefined values and creates matrix 'c' to store the result. Using nested loops, it iterates through each element of the resulting matrix 'c', calculating the dot product of corresponding row and column elements from matrices 'a' and 'b'. The computed result for each element is accumulated in the corresponding position of 'c'.

Conclusion

To sum up, arrays are essential data structures in Java that offer a practical means of storing and managing collections of elements. Java arrays include a number of benefits, such as support for both single- and multi-dimensional structures, fast random access, and effective data retrieval. Java arrays further facilitate code reusability and modular design by supporting the sending of arrays to methods and easy traversal and manipulation through a variety of loop structures.

Moreover, Java offers other capabilities that improve the functionality and adaptability of arrays in Java programming, including anonymous arrays, array cloning, and matrix operations like addition and multiplication. But it's important to understand that there are restrictions like finite size and possible runtime exceptions like ArrayIndexOutOfBoundsException.


Java Array MCQ

1. Which of the following statements is true regarding Java arrays?

  1. Java arrays can dynamically change their size.
  2. Java arrays can store elements of different data types.
  3. Java arrays are always initialized with default values.
  4. Java arrays do not allow duplicate elements.

Answer: c)

Explanation: In Java, arrays are initialized with default values (for example, 0 for numeric types, null for reference types, false for boolean). Java arrays have a fixed size once created, can store only one type of data, and allow duplicate elements.


2. Which of the following interfaces is implemented by Java arrays?

  1. List
  2. Cloneable
  3. Serializable
  4. Both B and C

Answer: d)

Explanation: Java arrays implement both Cloneable and Serializable interfaces, allowing arrays to be cloned and serialized.


3. What is an anonymous array in Java?

  1. An array without a specified type.
  2. An array declared without a name, used for a single-time use.
  3. An array that can change size dynamically.
  4. An array declared without specifying its size.

Answer: b)

Explanation: An anonymous array is an array without a reference name, created and used directly within a method call. For example, new int[]{1, 2, 3}.


4. What will happen if we try to access an element at an index that is greater than or equal to the array's length?

  1. The program will crash with a segmentation fault.
  2. The program will return a default value.
  3. The program will throw an ArrayIndexOutOfBoundsException.
  4. The program will compile but not run.

Answer: c)

Explanation: Accessing an array with an index outside its bounds will throw an ArrayIndexOutOfBoundsException.


5. Which method is used to copy elements from one array to another in Java?

  1. System.clone()
  2. System.arraycopy()
  3. Arrays.copy()
  4. Collections.copy()

Answer: b)

Explanation: The System.arraycopy() method is used to copy elements from one array to another. The syntax is System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length).


Related Topics

1) Java Program to copy all elements of one array into another array

2) Java Program to find the frequency of each element in the array

3) Java Program to left rotate the elements of an array

4) Java Program to print the duplicate elements of an array

5) Java Program to print the elements of an array

6) Java Program to print the elements of an array in reverse order

7) Java Program to print the elements of an array present on even position

8) Java Program to print the elements of an array present on odd position

9) Java Program to print the largest element in an array

10) Java Program to print the smallest element in an array

11) Java Program to print the number of elements present in an array

12) Java Program to print the sum of all the items of the array

13) Java Program to right rotate the elements of an array

14) Java Program to sort the elements of an array in ascending order

15) Java Program to sort the elements of an array in descending order

16) Find 3rd Largest Number in an Array

17) Find 2nd Largest Number in an Array

18) Find Largest Number in an Array

19) Find 2nd Smallest Number in an Array

20) Find Smallest Number in an Array

21) Remove Duplicate Element in an Array

22) Add Two Matrices

23) Multiply Two Matrices

24) Print Odd and Even Number from an Array

25) Transpose matrix

26) Java Program to subtract the two matrices

27) Java Program to determine whether a given matrix is an identity matrix

28) Java Program to determine whether a given matrix is a sparse matrix

29) Java Program to determine whether two matrices are equal

30) Java Program to display the lower triangular matrix

31) Java Program to display the upper triangular matrix

32) Java Program to find the frequency of odd & even numbers in the given matrix

33) Java Program to find the product of two matrices

34) Java Program to find the sum of each row and each column of a matrix

35) Java Program to find the transpose of a given matrix