What are the ways to print arrays in Java ?

Java Array is a data structure to store different elements of same data type. The elements in Java array are stored in contiguous memory. This sneppet will show you different ways to print arrays in Java.

Ways to print arrays in Java:

In Java, there are different ways to print an array. The following are the few common ways:

1. Using Arrays.toString() method:

The toString() method returns a string representation of the contents of the specified array. 

int[] array = {10, 20, 30, 40, 50};
System.out.println(Arrays.toString(array));

2. Using Arrays.deepToString()

This method can be used when you have to deal with two dimensional array. The deepToString(Object[]) method is a java. util. Arrays class method and it returns a string representation of the “deep contents” of the specified array.

String sneppets[][] = { { "Sneppets", "Content Writing" },
{ "Bing", "Search Engine" },
{ "Orkut", "Social Media" } };
System.out.println(Arrays.deepToString(sneppets));

3. Using a loop (for-each loop or regular for loop):

The for-each loop or regular for loop can be used to print an arrays as shown below.

int[] array = {10, 20, 30, 40, 50};

// Using a for-each loop
for (int element : array) {
   System.out.print(element + " ");
}

// Using a regular for loop
for (int i = 0; i < array.length; i++) {
   System.out.print(array[i] + " ");
}

4. Using Java 8 Streams:

The stream(array) creates a stream of elements from the array. The forEach method is then used with a method reference ( System. out::print ) to print each element of the array.

int[] array = {10, 20, 30, 40, 50};
Arrays.stream(array).forEach(element -> System.out.print(element + " "));

These are the different ways to print an array in Java. Hope it helped 🙂

You’ll also like:

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments