How to print array java

How to print array java

Java Array Methods – How to Print an Array in Java

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

An array is a data structure used to store data of the same type. Arrays store their elements in contiguous memory locations.

In Java, arrays are objects. All methods of class object may be invoked in an array. We can store a fixed number of elements in an array.

Let’s declare a simple primitive type of array:

Now let’s try to print it with the System.out.println() method:

Why did Java not print our array? What is happening under the hood?

If that object’s class does not override Object.toString() ‘s implementation, it will call the Object.toString() method.

Whenever we are creating our own custom classes, it is a best practice to override the Object.toString() method.

We can not print arrays in Java using a plain System.out.println() method. Instead, these are the following ways we can print an array:

Let’s see them one by one.

1. Loops: for loop and for-each loop

Here’s an example of a for loop:

All wrapper classes override Object.toString() and return a string representation of their value.

And here’s a for-each loop:

2. Arrays.toString() method

Arrays.toString() is a static method of the array class which belongs to the java.util package. It returns a string representation of the contents of the specified array. We can print one-dimensional arrays using this method.

Array elements are converted to strings using the String.valueOf() method, like this:

For a reference type of array, we have to make sure that the reference type class overrides the Object.toString() method.

This method is not appropriate for multidimensional arrays. It converts multidimensional arrays to strings using Object.toString() which describes their identities rather than their contents.

3. Arrays.deepToString() method

Arrays.deepToString() returns a string representation of the “deep contents” of the specified array.

Here is an example of the primitive type of multidimensional array:

If an element is an array of reference type, it is converted to a string by invoking Arrays.deepToString() recursively.

We have to override Object.toString() in our Teacher class.

If you are curious as to how it does recursion, here is the source code for the Arrays.deepToString() method.

NOTE: Reference type one-dimensional arrays can also be printed using this method. For example:

4. Arrays.asList() method

This method returns a fixed-size list backed by the specified array.

We have changed the type to Integer from int, because List is a collection that holds a list of objects. When we are converting an array to a list it should be an array of reference type.

Another example with our custom Teacher class:

NOTE: We can not print multi-dimensional arrays using this method. For example:

5. Java Iterator Interface

Similar to a for-each loop, we can use the Iterator interface to loop through array elements and print them.

Iterator object can be created by invoking the iterator() method on a Collection. That object will be used to iterate over that Collection’s elements.

Here is an example of how we can print an array using the Iterator interface:

6. Java Stream API

The Stream API is used to process collections of objects. A stream is a sequence of objects. Streams don’t change the original data structure, they only provide the result as per the requested operations.

With the help of the forEach() terminal operation we can iterate through every element of the stream.

Now we know how to print an array in Java.

Thank you for reading.

You can read my other articles on Medium.

Happy Coding!

How to Print an Array in Java

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

Introduction

Printing an array is a quick way to give us visibility on the values of the contents inside. Sometimes the array values are the desired output of the program.

In this article, we’ll take a look at how to print an array in Java using four different ways.

While the «best way» depends on what your program needs to do, we begin with the simplest method for printing and then show more verbose ways to do it.

Print an Array Using Arrays.toString() and Arrays.deepToString()

The built-in toString() method is an extremely simple way to print out formatted versions of objects in Java.

Take this example where we print the values of an array of integers:

The code above will output the following:

Note how all the elements are comma-separated and in square brackets. This method is like a visual representation of the array.

We can use this method to print arrays of different types as well:

These respectively result in:

The toString() method is only effective for one-dimensional arrays. When we have nested arrays we need use the deepToString() method:

These result in:

If you need a visual of what’s in your array at a glance, the toString() and deepToString() methods are your best option.

However, these methods don’t allow you to format your output. This approach is basically just a workaround for the fact that arrays don’t override the toString() method by default.

If you’d prefer some flexibility with the formatting, you might consider using Java 8 Streams.

Print an Array Using Java 8 Streams

One option for printing an array is to convert it to a stream of objects, then print each element in the stream. We have a few options to leverage streams to print our array.

For example, we can print our array line by line like this:

In this case, we use the static stream() method of the Arrays class to create a sequential stream of our data. For each element in our stream, we call the println() function on it, making it appear line by line like this:

Alternatively, we can use the Stream class from java.util.stream.Stream to similarly call the println() function on a stream of our array data. We can construct a Stream of this data using Stream.of() :

With this code we’ll get the same output:

Let’s try this out with nested arrays as well, adding the release dates of the initial versions of these languages:

The output for each print via streams would look something like this:

That doesn’t work very well. We’re calling println() on array objects again. We’ll have to stream those objects again, and print their elements.

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

To print nested arrays, we can use a lambda expression in the forEach() function that can go to the second level, by making another stream of each level, and printing the entries out that way:

This lambda function prints the elements in each nested array. When compiled and executed, we would get this output:

Streams make working with collections a breeze. But Java is flexible to provide even more ways. The traditional for-loop does a lot for us still. Let’s have a look at printing an array with loops.

Print an Array by Converting to List

You can easily convert a Java array into a List implementation. There are various ways to do that, and we’ve covered each in detail in our How to Convert a Java Array to ArrayList article.

This results in:

Though, this isn’t a nicely formatted option:

You can ditch the method reference and just use a lambda for more control:

This results in:

Print an Array Using For Loops

A more well-known approach to printing an array in Java is to use a for loop. With a for loop we get the index of the element, and we can use the index to get the element of an array.

Note: The number of elements in the array that will be used in the loop’s condition should never be hardcoded. Java provides an attribute called length that allows the programmer to dynamically calculate the number of elements in an array.

Last but not least, our for loop takes the incremental value in our case we will use the i++ notation to keep increasing our counter by one element in each iteration.

Here’s an example where we print all the elements of an integer array line by line:

Executing this code would print the following in your console:

There isn’t much more to using for loops. They’re quite flexible and conceptually simple. For example, if you had nested arrays then you’ll use nested for loops.

Finally, let’s have a look at iterators and lists.

Converting To List and Using an Iterator

A Java iterator object allows us to display each element of our array without having to use the index approach we covered in the for loop section.

Next, you will need an iterator object to set up your array iterator. An iterator is like a pointer that points to every element in the array. The iterator helps you to inspect each element in a singular manner.

Here’s an example where we take an array of integers and print each element line by line by using an iterator:

Conclusion

From there, we used streams so that we can quickly print array elements line by line. We’ve also covered how to convert an array to a list, which you can either just call or use the Java 8 Stream API for more granular control.

Then, we used the traditional for loop structure to print every element individually.

Last but not least, we used the iterator object to print every element separately using the next() method inside a while loop. The approaches covered in the chapter can be used depending on the use case and the problem you are trying to solve.

How to print array in java

In this post, we will see how to print array in java.

There are multiple ways to print an array. Let’s go through few ways to print array in java.

Using Arrays.toString()

You can use Arrays.toString() method to print array in java. This is simplest ways to print an array.
Arrays.toString() returns string object.This String contains array in string format.
Let us understand with the code

Output:

Using deepToString() method

Basically Arrays.toString() works fine for a 1-dimensional arrays,but it won’t work for multidimensional arrays.
Let’s say we have 2-dimensional array as shown
1 2 3
4 5 6
7 8 9
To convert multidimensional arrays to string, you can use Arrays.deepToString() method. This is how you can print 2D array in java.

Output:

Using Java 8 Stream API

In java 8, you can convert array to Stream and print array with Stream’s foreach() method.

Output:

As you can see we have seen how to print String array and Integer array in java using Stream.

Using for loop

You can iterate the array using for loop and print elements of array in java.

Output:

Using for-each loop

For each works same as for loop but with differs syntax.

Output:

Print array in reverse order in java

You can iterate the array using for loop in reverse order and print the element. This will print array in reverse order.

Output:

Print array with custom objects

In case, you have custom object in the array, then you should override toString() method in custom class, else it will give you unexpected results.
Let’s see with the help of example
Create a simple class named Color.java

Create main class named PrintArrayOfColors.java

Output:

If you notice, we don’t have toString() method in Color class, that’s why it is calling Object’s toString() method and we are not able to see meaningful results.

We need to override toString() method in Color class and we will get informative output.

When you run PrintListOfColorsMain again, you will get below output:

As you can see, we have much meaningful output now.

That’s all about how to print array in java.

Was this post helpful?

Share this

Initialize 2D array in Java

Write a Program to Find the Maximum Difference between Two Adjacent Numbers in an Array of Positive Integers

Author

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

Related Posts

How to Initialize an Array with 0 in Java

Table of ContentsArraysInitializing Newly Created ArrayUsing Default Initialization of Arrays in JavaUsing Initialization After DeclarationUsing Simultaneous Initializing and Declaration of ArrayUsing Reflection in JavaInitializing Existing ArrayUsing the Arrays.fill() Function of JavaUsing the for LoopUsing Reassignment From Another ArrayUsing Collections.nCopies() Function of JavaInitializing User-Defined Object ArrayConclusionWas this post helpful? This article discusses the arrays and different […]

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

Set an Array Equal to Another Array in Java

Table of ContentsSetting an Array Variable Equal to Another Array VariableSet an Array Equal to Another Array in Java Using the clone() MethodSet an Array Equal to Another Array in Java Using the arraycopy() MethodSet an Array Equal to Another Array in Java Using the copyOf() MethodSet an Array Equal to Another Array in Java […]

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

Check if Array Is Empty in Java

Table of ContentsCheck if the Array Is Empty in JavaThe Array Variable Has the Null ReferenceThe Array Does Not Contain Any ElementThe Array Has Only Null ElementsUsing the Java Library to Check if the Array Is Empty in JavaUsing Apache Commons Library to Check if the Array Is Empty in JavaConclusionWas this post helpful? In […]

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

Initialize empty array in java

Table of ContentsIntroductionHow do you initialize an empty array in java?Using new Keyword with predefined Values and SizeUsing Anonymous Array Objects to initialize empty arrayUsing java.util.Scanner Class for user input with predefined size. Using java.io.BufferedReader to initialize array for user input with unknown sizeUsing fill() method of java.util.Arrays Class to initialize empty arrayWas this post helpful? […]

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

Write a Program to Find the Maximum Difference between Two Adjacent Numbers in an Array of Positive Integers

In this article, we look at a problem : Given an Array of Positive Integers, Find the [Maximum Difference](https://java2blog.com/maximum-difference-between-two-elements-in-array/ «Maximum Difference») between Two Adjacent Numbers. For each pair of elements we need to compute their difference and find the Maximum value of all the differences in array. Let us look at an example, Consider this […]

Initialize 2D array in Java

Table of ContentsInitialize 2D array Using for loopInitialize 2D array using an initializerInitialize 2D array of variable columns lengthInitialize 2D array with heterogeneous dataInitialize 2D array using initialilzer with columnsInitialize 2D array using Reflection APIInitialize 2D array using the toCharArray()Was this post helpful? In this article, we will learn to initialize 2D array in Java. […]

How to print an array in java

will print something like [Ljava.lang.String;@5fdef03a.
Since an array is not an object of a user defined class, you cannot override toString method to print the array in a meaningful format.

import java.util.Arrays; public class ArrayToStringConverter < public static void main(String[] args) < String[] array = <"java", "python", "angular">; System.out.println(Arrays.toString(array)); > >

Above code prints

Method 2 : Using Arrays.asList method
java.util.Arrays class has a asList method which takes an array as argument and returns java.util.List object populated with the elements of array.
This list can be directly printed as shown below.

import java.util.Arrays; import java.util.List; public class ArrayToStringConverter < public static void main(String[] args) < String[] array = <"java", "python", "angular">; // convert array to list List list = Arrays.asList(array); System.out.println(list); > >

Above code prints

The reason that the list prints the above output is that the super class of all list implementations, that is, java.util.AbstractCollection has an overridden toString method which returns the list in string format as printed in the output.

import java.util.Arrays; public class ArrayToStringConverter < public static void main(String[] args) < String[] array = <"java", "python", "angular">; // join array elements with a comma String joinedString = String.join(«, «, array); System.out.println(joinedString); > >

java, python, angular

String joinedString = String.join(” “, array);

Method 4 : Using streams in java 8
java 8 also introduced the concept of streams which can be used to print a string array.
Example code which can be used to print array contents is given below.

Above code converts array to a list using asList method and then creates a stream of this list using stream method.
This stream is then iterated using forEach method. In every iteration, the current array element is received into the lamba expression provided to forEach as argument.
Output is

java python angular

Method 5 : Using for loop
This is a traditional method which iterates over an array using a for loop and prints the current element in every iteration.
This method is not a one-liner solution to print array.
Example,

java python angular

With this approach also, you can change the separator between elements of the array.

For any other method known to you, add in the comment box below.
Hit the clap below if you liked the article. Keep visiting.

Print Array in Java

By How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array javaChiranjan Saha

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

Introduction to Print Array in Java

An Array is basically a data structure where we can store similar types of elements. For example, an array of integers stores multiple integers, an array of strings stores multiple strings, etc. So if you have an Array with a large amount of data, you might need to print those to view them at your convenience with Print Array in Java. There are several ways that we can follow to print an array in Java. You can follow any of those methods to print an array. For each of the methods of Print Array in Java I will be discussing here, I have given examples of code for better understanding and hands-on purpose. I have also added comments inside the codes for better readability. Moreover, I have given screenshots of the output of each code. Go through the codes line by line and understand those. Then write and run those codes on yourself in java compilers and match those outputs with the given one.

Techniques to Print Array in Java

Below are the Techniques to Print Array in Java:

Web development, programming languages, Software testing & others

Method 1: Using for loop

As we know, a loop is used to execute a set of statements repeatedly until a particular condition is fulfilled. We will use this functionality of for loop to print the array here.

Example: 1

Here we will create an array of four elements and will use for loop to fetch the values from the array and print them.

Code:

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

Output:

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

The above example is for the one-dimensional array.

Example: 2

For a two-dimensional array, you will have both rows and columns those need to be printed out. So you will need to run two for loops in a nested fashion. One for rows and inside it, the other for columns.

Code:

Try it yourself and see the magic.

Method 2: Using the for-each loop

A for-each loop is also used to traverse over an array. As output, it will return elements one by one in the defined variable.

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

Example

We will create an array of four strings and iterate and print those using a for-each loop.

Code:

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

Output:

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

So far, we have used for and for-each sloops to print array. But from the next methods onwards, we will use classes related to the array under java. util packages which are specifically provided in java for the handling of arrays. We will use various static methods of those classes to deal with arrays. This will make our coding simple and hassle-free.

Let’s have a look at those ones by one.

Method 3: Using Java Arrays.toString()

The java.util.Arrays package has a static method Arrays.toString(). Hence, to use this static method, we need to import that package. Arrays.toString() accepts an array of any primitive type (for example, int, string) as its argument and returns the output as a string type.

Example: 1

This string type representation is a one-dimensional array. Hence, you can represent data in either rows or columns.

Code

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

Output:

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

Note the square brackets on the output. Square brackets denote the level of dimension. Thus, one pair (opening and closing pair) of the square bracket here denotes that the array is one dimensional.

Example: 2

For arrays with dimension two or larger, we cannot use Arrays.toString() method. Below is one example code:

Code:

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

Output:

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

This is happening as the method does not do a deep conversion. It will only iterate on the first dimension and call the toString() method of each item. Hence we are getting undesired results. What is the solution, then? Let’s have a look at our next method.

Method 4: Using Arrays.deep string() method

For arrays of dimension two or more, we will use the static method Arrays.deepToString(), which belongs to java.util.Arrays package. This method will do a deep conversion into a string of an array. Here also, the dimension of the array will be represented as a representation of square brackets.

Example

Code:

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

Output:

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

Note the square brackets representation. The square brackets are also 3 levels deep, which confirms the dimension of the array as three.

Method 5: Using Arrays.asList() method

The java.util.Arrays package has a static method Arrays.asList(). Hence, to use this static method, we need to import the package.

Example

Arrays.asList() accepts an array as its argument and returns the output as a list of an array.

Code:

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

Output:

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

Method 6: Using Iterator interface

The java.util.The iterator package has an interface Iterator. Hence, to use this interface for array printing, we need to import the package. We will create an Iterator object by calling the iterator() method. We will first convert the array into the list then invoke the iterator() method to create the collection. Then we will traverse through the collection using a while loop and print the values.

Example

As we need to convert the array into the list, we also need to use Arrays.asList() method and hence, also need to import java.util.Arrays.

Code:

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

Output:

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

Method 7: Using ArrayList( ) method

A normal array in Java is a static data structure because the initial size of the array is fixed. An ArrayList is a dynamic data structure where items can be added and removed from the list. So if you are not sure about how many elements will be there in your array, this dynamic data structure will save you. You need to import java.util.ArrayList package to use ArrayList() method to create ArrayList object. Once you have a new ArrayList object, you can add/remove elements to it with the add() /remove() method:

Example

Similar to Method 6. Here also, we will first convert the array into the list then invoke the iterator() method to create the collection. Then we will traverse through the collection using a while loop and print the values.

Code:

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

Output:

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

Method 8: Using Java Stream API

Example

We also can convert array to stream using the Arrays.stream() method. Then we iterate through the stream using foreach() and print them.

Code:

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

Output:

How to print array java. Смотреть фото How to print array java. Смотреть картинку How to print array java. Картинка про How to print array java. Фото How to print array java

This concludes our learning for the topic “Print Array in Java”. Practice the examples by writing the codes mentioned in the above examples. Learning of codes will be incomplete if you will not do hands-on by yourself. Happy coding!!

Recommended Articles

This is a guide to Print Array in Java. Here we have discussed the basic concept, Techniques to Print Array in Java with different methods along with codes and outputs. You can also go through our other related articles to learn more –

Java Training (40 Courses, 29 Projects, 4 Quizzes)

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *