In this post, we show the simplest way to print different types of Array in Java with an example.
Java library provides Arrays.toString(arr) or Arrays.deepToString(arr) methods to print string representation of the contents of the specified array.
Java library provides Arrays.toString(arr) or Arrays.deepToString(arr) methods to print string representation of the contents of the specified array.
Print Array in Java Example
package net.javaguides.corejava;
import java.util.Arrays;
public class ArrayExample {
public static void main(String[] args) {
String[] array = new String[] {
"John",
"Mary",
"Bob"
};
System.out.println(Arrays.toString(array));
String[][] deepArray = new String[][] {
{
"John",
"Mary"
}, {
"Alice",
"Bob"
}
};
System.out.println(Arrays.toString(deepArray));
//output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
System.out.println(Arrays.deepToString(deepArray));
double[] doubleArray = {
7.0,
9.0,
5.0,
1.0,
3.0
};
System.out.println(Arrays.toString(doubleArray));
int[] intArray = {
7,
9,
5,
1,
3
};
System.out.println(Arrays.toString(intArray));
}
}
Output:
[John, Mary, Bob]
[[Ljava.lang.String;@7852e922, [Ljava.lang.String;@4e25154f]
[[John, Mary], [Alice, Bob]]
[7.0, 9.0, 5.0, 1.0, 3.0]
[7, 9, 5, 1, 3]
Let's understand above program divided into small pieces:
Simple Array:
String[] array = new String[] {"John", "Mary", "Bob"};
System.out.println(Arrays.toString(array));
Output:
[John, Mary, Bob]
Nested Array:
String[][] deepArray = new String[][] {{"John", "Mary"}, {"Alice", "Bob"}};
System.out.println(Arrays.toString(deepArray));
//output: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
System.out.println(Arrays.deepToString(deepArray));
Output:
[[John, Mary], [Alice, Bob]]
double Array:
double[] doubleArray = { 7.0, 9.0, 5.0, 1.0, 3.0 };
System.out.println(Arrays.toString(doubleArray));
Output:
[7.0, 9.0, 5.0, 1.0, 3.0 ]
```
int Array:
int[] intArray = { 7, 9, 5, 1, 3 };
System.out.println(Arrays.toString(intArray));
Output:
[7, 9, 5, 1, 3 ]
Reference
Array
Java
String
Comments
Post a Comment