JAVA

JAVA – What’s the simplest way to print a Java array?

Printing array values in Java or values of array element in Java would have been much easier if arrays are allowed to directly prints its values whenever
  • Printing array values in Java or values of array element in Java would have been much easier if arrays are allowed to directly prints its values whenever used inside System.out.println() or format and printf method, Similar to various classes in Java do this by overriding toString() method.
  • Despite being an object, array in Java doesn’t print any meaningful representation of its content when passed to System.out.println() or any other print methods.
  • If we are using array in method argument or any other prominent place in code and actually interested in values of array then we don’t have much choice than for loop until Java 1.4. Things has been changed since Java 5 because it introduced two extremely convenient methods for printing values of both primitive and object arrays in Java.
  • Arrays.toString(array) and Arrays.deepToString(twoDimensionArray) can print values of any array.
  • Main difference between Arrays.toString() and Arrays.deepToString is that deepToString is used to print values of multidimensional array which is far more convenient than nesting of multiple for loops.

How to Print int array in Java

  • In order to print integer array, all you need to do is call Arrays.toString(int array) method and pass your integer array to it.
  • This method will take care of printing content of your integer array, as shown below.
  • If you directly pass int array to System.out.println(), we will only see type of array and a random number.
Java Code
int[] primes = {5, 7, 11, 17, 19, 23, 29, 31, 37};
System.out.println("Prime numbers : " + primes);
System.out.println("Real prime numbers : " + Arrays.toString(primes)); //Ok

Output:

Prime numbers : [I@5eb1404f
Real prime numbers : [5, 7, 11, 17, 19, 23, 29, 31, 37]

How to Print byte array in Java

  • printing byte array is no different than printing int array, as Arrays class provides an overloaded method toString(byte[] bytes) to print contents of byte array in Java, as shown below.
Java Code
String random = "In Java programming langue, array is object";
byte[] bytes = random.getBytes();
System.out.println("What is inside bytes : " + bytes);
System.out.println("Not visible, check closely .." + Arrays.toString(bytes));

Output

What is inside bytes : [B@31602bbc
Not visible, check closely ..[73, 110, 32, 74, 97, 118, 97, 32, 112, 114, 111, 103, 114, 97, 109, 109, 105, 110, 103, 32, 108, 97, 110, 97, 103, 117, 101, 44, 32, 97, 114, 114, 97, 121, 32, 105, 115, 32, 111, 98, 106, 101, 99, 116]

READ  [ Solved -8 Answers ] JAVA - Java function for arrays like PHP's join()?

How to Print String array in Java

  • Printing string array in Java is probably easiest thing to do, because Arrays class has another overloaded version of toString() to accept Object.
  • This method calls toString() of Object to get a printable String.
  • This can also be used to print array of any arbitrary object in Java. User defined object must override toString() method to show something reasonable on console.
Java Code
String[] buzzwords = {"Java", "Android", "iOS", "Scala", "Python"};
System.out.println("Buzzing .." + buzzwords);
System.out.println("Not buzzing? try again : " + Arrays.toString(buzzwords));

Output:

Buzzing ..[Ljava.lang.String;@46f5331a
Not buzzing? try again : [Java, Android, iOS, Scala, Python]

How to Print Two Dimensional array in Java

  • How to print Array in Java with exampleArrays class provides a different method to print two dimensional array in Java, it’s called toDeepString().
  • It’s capable of printing multi-dimensional array in Java and similar to toDeepEquals() which is used to compare multi-dimensional array in Java.
  • This method is also overloaded and provides 8 + 1 primitive and object versions to accept boolean, byte, short, char, int, long, float, double and Object in Java.

Here is an example of how to print two dimensional array in Java.

Java Code
String[][] phones = {{"Apple", "iPhone"}, {"Samsung", "Galaxy"}, {"Sony", "Xperia "}};
System.out.println("Hot phones .. " + phones); 
System.out.println("Not hot? See again.." + Arrays.deepToString(phones)); 

Output

Hot phones .. [[Ljava.lang.String;@57398044
Not hot? See again..[[Apple, iPhone], [Samsung, Galaxy], [Sony, Xperia]]

Print Array Value Example 1: Using for loop

  • for loop is the classical way of printing or displaying values of both one dimension and multidimensional arrays in Java. before Java 5 you can use array.length to iterate over all array elements and printing values for each of them.
  • From Java 5 onwards you can use much cleaner enhanced for loop which doesn’t require any counter from moving one element to other in Java.
  • Enhanced for loop in Java 5 is added with other popular language feature e.g. Enum, Autoboxing and Generics.
READ  Java Programming - Count of n digit numbers whose sum of digits equals to given sum

Here is sample code example to print value of element from array using classical and enhanced for loop in Java:

Java Code
// Classic for loop before Java 5
private static int[] iArray = new int[]{1, 2,3,4, 5};

for(int i=0; i< iArray.length; i++){
   System.out.print(iArray[i] +", ");
}

Output:
1, 2, 3, 4, 5,

Java Code
//Enhanced for loop from Java 1.5
for(int i : iArray){
   System.out.print(i +", ");
}

Print Array Values Example 2: Using Arrays.asList

  • Arrays.asList() method is used to convert Array into ArrayList and as you know Collection classes overrides toString method to print there contents.
  • By converting array into List we can leverage that property and print values from ArrayList instead of Array.
  • Only limitation of this approach is it doesn’t print contents of array if array is of primitive type like int, float or double but works well if Array contains objects like String.
  • Arrays.asList() is also used to create and initialize List in one line.

By the way here is simple code example of displaying values form array in Java using Arrays.asList() method:

Java Code
System.out.println("Print String array values in Java 1.4 :" + Arrays.asList(sArray));
System.out.println("Print int array values in Java 1.4 :" + Arrays.asList(iArray));

Output:

Print String array values in Java 1.4 :[abc, bcd, def, efg] Print int array values in Java 1.4 :[[I@15b7986]

Print Array Value Example 3: using Arrays.toString and Arrays.deepToString

  • This is by far best and recommended way of printing values from Array in Java.
  • Only caveat is that Arrays.toString() and Arrays.deepToString() are added from Java 5 onwards along with other features e.g. Generics, varargs or static import.
  • Use Arrays.toString() method to print both primitive and object single or one dimension array and use Arrays.deepToString() method to print values from two dimensional or multidimensional array (array of array in Java).
READ  Longest Even Length Substring such that Sum of First and Second Half is same

Here is a simple example of printing array values using Arrays.toString() and Arrays.deepToString() in Java:

Java Code
System.out.println("Print values of Integer array in Java: " + Arrays.toString(iArray));System.out.println("Print values of String array in Java: " + Arrays.toString(sArray));      int[][] twoDimensionArray = new int[][]{                                    {1,2,3},                                    {10,20,30},                                    {100,200,300},                                    };System.out.println("Print two dimensional array in Java: " + Arrays.deepToString(twoDimensionArray));

Output:

Print values of Integer array in Java: [1, 2, 3, 4, 5]

Print values of String array in Java: [abc, bcd, def, efg]

Print two dimensional array in Java: [[1, 2, 3], [10, 20, 30], [100, 200, 300]]

JDK 8 Stream
In JDK 8, we can convert it to Stream and print it.

Java Code
PrintArray.java
package com.mkyong.utils.print;

import java.util.Arrays;

public class PrintArray {

    public static void main(String[] args) {

        // array
        String[] arrayStr = new String[]{"Java", "Node", "Python", "Ruby"};
        Arrays.stream(arrayStr).forEach(System.out::println);

        int[] arrayInt = {1, 3, 5, 7, 9};
        Arrays.stream(arrayInt).forEach(System.out::println);

Java Code
//2d array
        String[][] deepArrayStr = new String[][]{{"mkyong1", "mkyong2"}, {"mkyong3", "mkyong4"}};
        Arrays.stream(deepArrayStr).flatMap(x -> Arrays.stream(x)).forEach(System.out::println);

        int[][] deepArrayInt = new int[][]{{1, 3, 5, 7, 9}, {2, 4, 6, 8, 10}};
        Arrays.stream(deepArrayInt).flatMapToInt(x -> Arrays.stream(x)).forEach(System.out::println);

    }

}

Json Anything
Use Jackson2 library to print anything in a JSON formatted string.

PrintUtils.java

Java Code
package com.mkyong.utils.print;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class PrintUtils {

    private static final ObjectMapper om = new ObjectMapper();

	public static void print(Object object) {
		String result;
		try {
			result = om.writerWithDefaultPrettyPrinter().writeValueAsString(object);
            System.out.println(result);
Java Code
 } catch (JsonProcessingException e) {
			e.printStackTrace();
		}
	}

}

PrintArray.java

Java Code
package com.mkyong.utils.print;

public class PrintArray {

    public static void main(String[] args) {

		//array
        String[] arrayStr = new String[]{"Java", "Node", "Python", "Ruby"};
        PrintUtils.print(arrayStr);

Java Code
int[] arrayInt = {1, 3, 5, 7, 9};
        PrintUtils.print(arrayInt);

		//2d array
        String[][] deepArrayStr = new String[][]{{"mkyong1", "mkyong2"}, {"mkyong3", "mkyong4"}};
        PrintUtils.print(deepArrayStr);

        int[][] deepArrayInt = new int[][]{{1, 3, 5, 7, 9}, {2, 4, 6, 8, 10}};
        PrintUtils.print(deepArrayInt);

    }

}

Output

[ “Java”, “Node”, “Python”, “Ruby” ] [ 1, 3, 5, 7, 9 ] [ [ “mkyong1”, “mkyong2” ], [ “mkyong3”, “mkyong4” ] ] [ [ 1, 3, 5, 7, 9 ], [ 2, 4, 6, 8, 10 ] ]

 

About the author

Venkatesan Prabu

Venkatesan Prabu

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

1 Comment

Click here to post a comment