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:
- Python program to find difference between two given numbers
- Python Programs to Print Patterns – Pyramid, Triangle using Star
- Java Palindrome Program- Check String or Number is Palindrome
- Sort an array of objects by a string property value ?
- Program to Check Given Number is Odd or Even
- Convert single digit number to double digits string
- Find the greatest of three numbers
- Most Common Element in an Unsorted Array
- Get Common Elements between Two Unsorted Arrays
- Implement Stack using Linked List
- Convert negative to positive number in Python
- TypeError: a bytes-like object is required, not ‘str’ – Python3
- Extract numbers from a string in python
- Java String substring() example program
- Find which users belongs to a specific group in linux
- print multiplication table for any number
- Check if Python Object is a Number ?
- In-place merge sort instead of normal merge sort ?