Programs

Java Program to Print Array

Basics of Java Array

An array in Java is a collection of similar items that are referred to a single name. Java arrays are slightly different from the arrays of other object-oriented programming languages. Some important facts about the arrays used in Java are:

  • The arrays in Java are dynamically assigned.
  • An array variable can be declared like any other Java variables by specifying [] after the mention of the data type.
  • The contents of an array are sequenced and each array variable is specified by an index that starts from 0. i.e. the first array element is in the 0th index, the second element is in the first index and so on.
  • The arrays in Java can be used as a local variable or a static field or a method parameter. 
  • The array size can be either int or short type. Long values cannot be assigned as array size. 
  • An Object is the direct superclass of the type array. 
  • The Cloneable and java.io.Serializable interfaces are implemented by each array type.

Check out our free technology courses to get an edge over the competition.

Explore our Popular Software Engineering Courses

Why Is It Necessary For Java To Print Arrays?

Now that we know how to print an array in Java, we also need to understand the why. Java offers the Array data structure to hold various components of the same data type. Contiguous memory is used to store the items. The array’s elements must be printed in order to show similar contents. 

Important Facts About Printing Array In Java

When you understand Java how to print array, you need to remember these important facts. 

  • The array is changed into a list using the Arrays.asList() method.
  • The multidimensional array’s items are converted to string type using the Arrays.deepString() method.
  • The 1d array’s elements are converted to string type using the Arrays.toString() method.
  • The array elements are changed to a stream using the Arrays.stream() method.

Performance Implications of Different Approaches 

With a small array’s printing come lesser differences in performance. However, when we deal with large arrays, the time involved in printing can be significant. Therefore, when printing arrays, assessing the performance implications of the approach you opt for is vital.

For instance, the for-loop method prints each element one by one. It can be inefficient for large arrays because it involves iterating all array elements. Comparatively, the Arrays.toString() method converts the array to a string representation and prints it more efficiently as it avoids iterating over all array elements. It is noteworthy that even this method encounters limitations when we deal with multidimensional arrays. When learning how to print string array in Java, remember the Arrays.deepToString() method is best suitable for multidimensional arrays as it gives a string representation of the array that includes all nested arrays. It is far more efficient than using nested for-loops for printing. 

Additionally, third-party libraries such as Apache Commons Lang or Guava can provide extra formatting options as well as performance optimization that are often useful for printing large arrays.

How to Format the Output when Printing Arrays?

Typically, the output of an array is printed as a series of elements that are separated by commas and stay enclosed in square brackets. There are several ways to alter the formatting of the output when printing Java arrays, for instance

  • String.format() method to specify a custom format specifier
  • Replace() method to replace the commas with newlines
  • Third-party libraries like Apache Commons Lang or Guava 

Additionally, the String.format() method helps specify the number of decimal places to display. Thus, these methods help control the output’s spacing, precision, and alignment and make it easier to read and understand.

Printing an Array in Java:

A data structure that stores the items of the same data type is called an array in Java. The array elements are allocated in a contiguous storage location. So, a fixed set of items can be stored in an array. There are several ways in which an array can be printed. They are:

  • For loop
  • For-each loop
  • Arrays.toString() method
  • Arrays.deepToString() method
  • Arrays.asList() method
  • Iterator Interface in Java
  • Stream API in Java

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

In-Demand Software Development Skills

How to print an array in Java using for-each loop?

The ‘for-each’ loop in Java is also used to iterate over an array of items. It works based on the number of elements in the array. For each iteration, one element is returned by the loop in the defined variable. The syntax of ‘for-each’ loop is as follows:

for(Type var:array) 

Read our Popular Articles related to Software Development

Use of Arrays.toString() method to print an array in Java:

This static method in Java is of array class and is a constituent of java.util package. It consists of several methods that can manipulate an array. The syntax of the Arrays.toString() method in Java is as mentioned below.

public static String toString(int[] a)

This method takes an array with any primitive type as an input argument. It returns an array in a string form and consists of a list of elements of the array. The conversion of the array’s elements into a string is done by the String.valueOf(int).

How to print an array in Java using Arrays.deepToString() method:

When this method is invoked, a multidimensional array is converted into a string of array elements. This function needs an input argument in the form of an array. It returns the array representation in the form of a string. The syntax of this method in Java is as specified below.

public static String deepToString(Object[] a)

Arrays.asList() method to print an array of elements in Java:

This is also a static Java method of Arrays class that belongs to the package java.util. It acts as a connection between the collection based and the array-based API. The syntax in which this method is used in a Java code is mentioned below. 

public static <T> List<T>asList(T…a)

This method also enables the user in developing a list of fixed sizes that can be initialized to accommodate many elements.

List<T>obj=Arrays.toString(array[] a

This method returns the input array in the list form. 

Use of Iterator Interface to Print an array in Java:

The Java Iterator is an interface constituted in the java.util package. The creation of an Iterator can be done by invoking the iterator() method. This function is with the collection interface of Java and the returned value is also an iterator. 

Other array functions in Java:

Apart from printing an array, the Java compiler performs various other array functions, a few of which are listed below. 

  • Fetch the initial and final element of an array.
  • Fetch an arbitrary array element.
  • Insert a new element into an array.
  • Comparison of two arrays.
  • Check if an array is empty or not.

If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-B’s Executive PG Programme in Software Development – Specialisation in Full Stack Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Want to share this article?

Prepare for a Career of the Future

Leave a comment

Your email address will not be published. Required fields are marked *

Our Popular Software Engineering Courses

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks