Arrays are capable of storing multiple elements that share the same data type. In programming languages, arrays are the backbones of many algorithms and data structures. Therefore, printing an array is crucial to extract meaningful insights. In Java, developers use different built-in methods, loops, APIs, etc for printing the array.
Quick Outline
This article covers the following aspects of printing an array in Java:
Print an Array Using the Built-in Methods
In an array, each index stores a specific element. The simplest method for printing an array in Java is to specify the index of each element individually. However, it is not an ideal practice when it comes to arrays with dynamic lengths:
int [ ] numArray = { 1, 2, 3, 4, 5 };
System.out.println("Index 0 elements is : " + numArray[0]); // by default, array index starts from 0
System.out.println("Index 1 elements is : " + numArray[1]);
System.out.println("Index 2 elements is : " + numArray[2]);
System.out.println("Index 3 elements is : " + numArray[3]);
System.out.println("Index 4 elements is : " + numArray[4]);
Complete Code & Output
Print Array Using Control Flow Statements
The control flow statements control the execution flow of the code. Loops are the fundamental parts of the programming that iteratively execute the compound statements for a specific condition. Below listed are the loop statements in Control flow statements:
- For loop
- While loop
- Do-while loop
- Enhanced for Loop
Method 1: Printing Array Using For loop
The for loop repeatedly traverses the compound statements as long as the condition is true. The basic syntax of the for loop is given as follows:
for (initialization; condition; increment)
{ //logic of the program
}
In the following code, a string array “strArray” is initialized with the respective elements. The for loop traverses through the array’s elements and exits when “i” is greater than the array’s length. In each iteration, the element at the current index “strArray[i]” ”is printed and the value of “i” is incremented by “1” to move to the next index:
String[ ] strArray = {"Welcome", "to ", "Java "} ;
for (int i=0; i<strArray.length; i++)
{
System.out.println("Index " + i + " = " + strArray[i]);
}
Complete Code & Output
Method 2: Printing an Array Using the While Loop
The while loop works similarly to the “for loop”. However, the number of iterations is not known in the while loop. Below is the basic syntax of the while loop:
while(condition)
{
//program logic
}
The while loop checks the condition if the value of “i” is less than the length of the array (strArray.length). The print statement displays the element of the array at the current index that is pointed by the “i” variable “strArray[i]”. In each iteration, the value of “i” advances by 1, and the loop exits when the array’s length is less than the value of “i”. The code is as follows:
String[ ] strArray = {"Welcome" , "to ", "Java "} ; // initializes the array
int i=0; // integer variable that starts with 0
while (i < strArray.length)
{
System.out.println("Array index " + i + " = " + strArray[i]); i++;
}
Complete Code & Output
Method 3: Printing an Array Using the Do-while Loop
The do-while loop executes the block of code at least once and then checks the condition afterward. The syntax is given as follows:
do
{
//program logic
}while(condition);
The do-while loop will print the element at the “0” index of the array. The value of “i” will be incremented in each loop iteration. The do-while loop continues to execute till “i” is less than the total length of the array. Similarly, the loop terminates when “i” exceeds the length of the array:
String[ ] strArray = {"Welcome" , "to ", "Java "}; // string array is created
int i=0; // integer variable used to point to the index of the array
do
{
System.out.println("Array index " + i + " = " +strArray[i]);
i++;
} while(i<strArray.length); // condition to be checked
Complete Code & Output
Method 4: Printing an Array Using the Enhanced For Loop
The enhanced for loop works similarly to the “for loop”. It is an alternative and more efficient approach to iterate over the elements of an array than the for loop. The syntax of this loop is given below:
for ( data type iterator : array)
{
//program logic
}
Within this code, the enhanced for loop iterates over the “numArray” using the “number” as an iterator. The output is printed as shown in the code below:
int [ ] numArray= {1, 2, 3, 4}; // creates an integer array with given values
for ( int number : numArray)
{
System.out.println("Current element = " + number );
}
Note: The data type of the iterator and the array must be the same in the enhanced for loop.
Complete Code & Output
Print an Array Using Built-in Method
In Java, there are different built-in methods to print the array elements. For this, you can use toString(), deepToString(), and asList() methods.
Method 1: Printing an Array Using toString()
The “toString()” method is provided by the Arrays class of the “java.util” package. It is a static built-in method that returns an object in the string representation. The basic syntax is as follows:
public static Arrays.toString(arrayname);
The following line of code imports the “Arrays” class from the “util” package to use the “toString()” method:
import java.util.Arrays;
An integer “numArray” is created with the given values. The “numArray” is passed to the toString() method of the “Arrays” class and the output is printed:
int [ ] numArray= {1,2,3,4};
System.out.println("Array Elements are : " + Arrays.toString(numArray));
Complete Code & Output
Method 2: Printing an Array Using the deepToString()
The deepToString() method of the “Arrays” class provides a string representation of each element of a multidimensional array. Given below is the basic syntax of this instance:
public static Arrays.deepToString(Object [ ])
Within the given code, a multidimensional 2D array is created. The “Arrays” class invokes the static deepToString() method that takes numArray as an argument. The output is displayed using the print statement:
int [ ][ ] numArray= {{1, 2, 3} , {4, 5, 6, 7}, {8, 9, 10 } };
System.out.println("Array Elements are : " + Arrays.deepToString(numArray));
Note: The deepToString() method cannot be used for the single-dimensional arrays.
Complete Code & Output
Method 3: Printing an Array Using the asList()
The “asList()” is a static built-in method of the Arrays class that converts an array into a list. The basic syntax of the “asList()” method is given as
public static Arrays.asList()
The “strArray” is passed as an argument to the asList() method of the Arrays class:
String [ ] strArray = {"Printing", "Array " , "using " , "asList()" };
System.out.println("Array Elements are : " + Arrays.asList(strArray));
Complete Code And Output
Comparison of toString(), deepToString() and asList() Method
Below is a comparison of the three methods:
toString() | deepToString() | asList() |
---|---|---|
The “toString()” method functions for the single-dimensional arrays. | The “deepToString()” method is suitable for multidimensional arrays. | The “asList()” method works for the Lists in Java. |
The toString() method converts elements of a 1D array into a string or text representation and returns it. | The deepToString() method returns a string representation of each element of a multidimensional array | The asList() method accepts an array as an argument and converts it into a list. The list size cannot be modified. |
Print an Array Using an Interface
Interface in Java allows the user to achieve abstraction by defining abstract methods and constants. In other words, the interface is similar to a class that declares related methods but does not define them. Different classes can implement an interface if the class contains required methods, types, or constants.
The iterator is a Java interface that is used to traverse the collection of objects. The iterator interface performs both read and delete operations and does not incur any charges. The following line of code imports Iterator, Arrays, and List from the util package:
import java.util.*;
The string array “stringArray” is created with the following elements. The “Arrays.asList()” converts the “stringArray” into a list:
String[] stringArray = {"Welcome ", " to ", " JavaBeat "};
List<String> list = Arrays.asList(stringArray);
In this section of the code, an iterator of string type is created to traverse the elements of the list.
The iterator.hasNext() returns true if there is any next element for printing and false if there are no elements. The loop will terminate when there are no more elements left to print in the array:
Iterator<String> iterator = list.iterator();
while(iterator.hasNext())
{
System.out.print(iterator.next());
}
Complete Code And Output
Print an Array Using the Stream API
The Stream API is a new feature introduced by Java 8. Developers can utilize this API to access and manipulate Collections or arrays by using different static methods. This section of the article implements the Stream API for printing an array in Java.
The Arrays class from the “java.utils” package which is included as follows:
import java.util.Arrays;
The “Arrays.stream()” accepts the integer array and converts it into an integer stream. The “forEach” method iterates over the integer stream and prints it:
int[] array = {1, 2, 3, 4, 5}; //creates an integer array
Arrays.stream(array).forEach(System.out::println);
Complete Code And Output
That is all from this guide.
Conclusion
To print an Array in Java, there are loops like for loop, while loop, etc, built-in methods e.g., toString(), asList(), etc, or using APIs such as Stream API. Aside from these methods, the array elements can also be printed by specifying the index of each element. However, it is not encouraged as it is not suitable for arrays with variable lengths. This article provides multiple distinct methods for printing the array in Java.