import java.util.Arrays;
public class Simple5WaysToPrintJavaArray {
public static void main(String[] args) {
int[] intArray = new int[] {1, 2, 3, 4, 5};
String[] strArray = new String[] {"John", "Mary", "Bob", "Don", "Chris"};
//Method 1 - This will be useful to print using prior versions of Java 8
System.out.println(Arrays.toString(intArray));
System.out.println(Arrays.toString(strArray));
// Method 2 - In Java 8 we have lambda expressions
Arrays.stream(intArray).forEach(System.out::print);
System.out.println("");
Arrays.stream(strArray).forEach(System.out::print);
System.out.println("");
//Method 3 - using a for loop - using one loop as the lengths are same
for (int i = 0; i < intArray.length; i++) {
System.out.print(intArray[i] + ", ");
System.out.print(strArray[i] + ", ");
}
System.out.println("");
//Method 4 - using Arrays.asList - only works with String as int is primitive
System.out.println(Arrays.asList(strArray));
//Method5 - using extended for loop from Java 5
for(int i:intArray){
System.out.print(i+ ", ");
}
System.out.println("");
for (String str : strArray) {
System.out.print(str+ ", ");
}
}
}
Sunday, October 28, 2018
5 simple ways to print java array
You can print a Java array in so many different ways depending upon your Java version. I have collated 5 easy and simple ways to print arrays in Java.
Output:
[1, 2, 3, 4, 5]
[John, Mary, Bob, Don, Chris]
12345
JohnMaryBobDonChris
1, John, 2, Mary, 3, Bob, 4, Don, 5, Chris,
[John, Mary, Bob, Don, Chris]
1, 2, 3, 4, 5,
John, Mary, Bob, Don, Chris,
Labels:
Core Java
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment