- How to print array in java
- Using Arrays.toString()
- Using deepToString() method
- Using Java 8 Stream API
- Using for loop
- Using for-each loop
- Print array in reverse order in java
- Print array with custom objects
- Was this post helpful?
- Share this
- Related Posts
- Author
- Related Posts
- Create Array from 1 to n in Java
- How to Print 2D Array in Java
- Return Empty Array in Java
- How to Write Array to File in Java
- How to Initialize an Array with 0 in Java
- Set an Array Equal to Another Array in Java
- Как напечатать массив в Java
- С помощью команды «toString»
- Как распечатать двумерный массив в java
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
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.
Using Java 8 Stream API
In java 8, you can convert array to Stream and print array with Stream’s foreach() method.
Arrays . stream ( string2DArray ) . flatMap ( str — > Arrays . stream ( str ) ) . forEach ( System . out : : println ) ;
Arrays . stream ( int2DArray ) . flatMapToInt ( i — > Arrays . stream ( i ) ) . forEach ( System . out : : println ) ;
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.
Using for-each loop
For each works same as for loop but with differs syntax.
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.
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
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
Next Write a Program to Find the Maximum Difference between Two Adjacent Numbers in an Array of Positive Integers
Related Posts
Author
Related Posts
Create Array from 1 to n in Java
Table of ContentsIntroductionArray in JavaCreate Array from 1 to N in JavaUsing Simple For loop in JavaUsing IntStream.range() method of Stream API in JavaUsing IntStream.rangeClosed() method of Stream API in JavaUsing IntStream.iterate() method of Stream API in JavaUsing the Stream class of Stream API in JavaUsing Arrays.setAll() method in JavaUsing Eclipse Collections Framework in JavaUsing […]
How to Print 2D Array in Java
Table of ContentsIntroductionWhat is a 2-dimensional array or matrix in java?How to print a 2D array in java?Simple Traversal using for and while loopUsing For-Each Loop to print 2D Array in JavaArrays.toString() method to print 2D Array in JavaArrays.deepToString() method to print 2D Array in JavaUsing Stream API in Java 8 to print a 2D […]
Return Empty Array in Java
Table of ContentsWhat Is the Need to Return an Empty Array?How Do You Return Empty Array in Java?Using Curly Braces to Return Empty Array in JavaUsing Anonymous Array Objects – New Int[0] to Return Empty Array Using Empty Array Declaration to Return Empty Array in JavaUsing Apache Commons Library – Array Utils Package to Return Empty […]
How to Write Array to File in Java
Table of ContentsWays to Write Array to File in JavaUsing BufferWriterUsing ObjectOutputStream In this post, we will see how to write array to file in java. Ways to Write Array to File in Java There are different ways to write array to file in java. Let’s go through them. Using BufferWriter Here are steps to […]
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 ArrayConclusion This article discusses the arrays and different ways to initialize […]
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 […]
Как напечатать массив в Java
В создании этой статьи участвовала наша опытная команда редакторов и исследователей, которые проверили ее на точность и полноту.
Команда контент-менеджеров wikiHow тщательно следит за работой редакторов, чтобы гарантировать соответствие каждой статьи нашим высоким стандартам качества.
Количество просмотров этой статьи: 21 536.
Если вы работаете в Java и у вас массив с большим объемом данных, возможно, удобства ради, вам стоит напечатать определенные элементы. Существует несколько способов напечатать массивы в Java, и примеры, приведенные дальше, покажут, как это сделать. Для этого предположим, что название массива будет напечатано как «array», а искомые элементы – «Elem».
С помощью команды «toString»
Настройте элементы в массиве. Введите String[] array = new String[] , где «ElemX» – это отдельные элементы в массиве.
Используйте библиотеку стандартного статического метода: Arrays.toString(array) . Это даст вам строковое представление одномерных массивов. Другими словами, благодаря тому, что массив одномерный, данные можно представить либо в виде строк, либо в виде столбцов. Данный метод напечатает данные в ряд или в строку. [1] X Источник информации
Выполните программу. Разные компиляторы по-разному выполняют эту задачу. Нажмите «Файл», а затем «Выполнить» или нажмите на значок «Выполнить» на панели инструментов. Элементы будут напечатаны в строку в нижнем окне Java.
Как распечатать двумерный массив в java
Массивы в Java относятся к ссылочному типу данных, поэтому обычный способ печати не сработает, мы не увидим содержимое массивов. Прежде, чем вывести массив на экран, нужно привести его и все вложенные массивы к строковому представлению. Для этого в классе Arrays есть метод deepToString() , который возвращает строковое представление многомерного массива на всю глубину:
import java.util.Arrays; int[][] coll = 1, 2>, 3, 4>>; var stringRepresentation = Arrays.deepToString(coll); System.out.println(stringRepresentation); // => [[1, 2], [3, 4]]