Monday, 17 August 2015

Simplest way to print array in Java

Following are the simplest ways to print array in java.

Method 1:
System.out.println(Arrays.toString(arr));

Method 2: deepToString is used to print multi dimensional arrays.
System.out.println(Arrays.deepToString(arr));

Method 3:
System.out.println(Arrays.asList(arr));

Method 4: (Works in Java8 and above).
Arrays.stream(arr).forEach(System.out::println);

import java.util.Arrays;

public class PrintArray {

 public static void main(String args[]) {
  Object[] arr = { 1, 2, 3, 4, 5 };

  /* Method 1 */
  System.out.println(Arrays.toString(arr));

  /* Method 2 */
  System.out.println(Arrays.deepToString(arr));

  /* Method 3 */
  System.out.println(Arrays.asList(arr));

  /* Method 4 (Works in Java8 only) */
  Arrays.stream(arr).forEach(System.out::println);

 }
}


Output
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
1
2
3
4
5


No comments:

Post a Comment