How to print multi-dimensional array using for-each loop in java? I tried, foreach works for normal array but not work in multi-dimensional array, how can I do that? My code is:
class Test
{
public static void main(String[] args)
{
int[][] array1 = {{1, 2, 3, 4}, {5, 6, 7, 8}};
for(int[] val: array1)
{
System.out.print(val);
}
}
}
Your loop will print each of the sub-arrays, by printing their address. Given that inner array, use an inner loop:
for(int[] arr2: array1)
{
for(int val: arr2)
System.out.print(val);
}
Arrays don't have a String
representation that would, e.g. print all the elements. You need to print them explicitly:
int oneD[] = new int[5];
oneD[0] = 7;
// ...
System.out.println(oneD);
The output is an address:
[I@148cc8c
However, the libs do supply the method deepToString
for this purpose, so this may also suit your purposes:
System.out.println(Arrays.deepToString(array1));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With