Overview
In this tutorial, we show you 5 ways to print a Array in Java.
Print Array using Arrays.toString() method
package com.jackrutorial;
import java.util.Arrays;
public class PrintArrayExampleExample1 {
public static void main(String[] args) {
String[] programmingLanguages = new String[] {"Java", "Spring Boot", "Spring MVC", "AngularJS", "ReactJS", "Android"};
System.out.println(Arrays.toString(programmingLanguages));
}
}
Output
[Java, Spring Boot, Spring MVC, AngularJS, ReactJS, Android]
Print Array using the for loop in java
package com.jackrutorial;
public class PrintArrayExampleExample2 {
public static void main(String[] args) {
String[] programmingLanguages = new String[] {"Java", "Spring Boot", "Spring MVC", "AngularJS", "ReactJS", "Android"};
StringBuffer strbf = new StringBuffer();
for(int i = 0; i< programmingLanguages.length; i++) {
if(i > 0) {
strbf.append(", ");
}
strbf.append(programmingLanguages[i]);
}
System.out.println(strbf);
}
}
Output
Java, Spring Boot, Spring MVC, AngularJS, ReactJS, Android
Print Array using java.util.Arrays.stream() method in JDK 8
package com.jackrutorial;
import java.util.Arrays;
public class PrintArrayExampleExample3 {
public static void main(String[] args) {
String[] programmingLanguages = new String[] {"Java", "Spring Boot", "Spring MVC", "AngularJS", "ReactJS", "Android"};
Arrays.stream(programmingLanguages).forEach(System.out::println);
}
}
Output
Java
Spring Boot
Spring MVC
AngularJS
ReactJS
Android
Print Array using Arrays.deepToString() method
The
java.util.Arrays.deepToString(Object[]) method returns a string representation of the "deep contents" of the specified array. If the array contains other arrays as elements, the string representation contains their contents and so on.
package com.jackrutorial;
import java.util.Arrays;
public class PrintArrayExampleExample4 {
public static void main(String[] args) {
String[][] programmingLanguages = {{"Java", "PHP", "C#"}, {"MySQL", "SQL", "Oracle"}};
System.out.println(Arrays.deepToString(programmingLanguages));
}
}
Output
[[Java, PHP, C#], [MySQL, SQL, Oracle]]
Print Array using Stream.flatMap() in JDK 8
Using
Stream.flatMap() we will get stream of the programming language from all the programming languages.
package com.jackrutorial;
import java.util.Arrays;
public class PrintArrayExampleExample5 {
public static void main(String[] args) {
String[][] programmingLanguages = {{"Java", "PHP", "C#"}, {"MySQL", "SQL", "Oracle"}};
Arrays.stream(programmingLanguages).flatMap(x -> Arrays.stream(x)).forEach(System.out::println);
}
}
Output
Java
PHP
C#
MySQL
SQL
Oracle