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:
Arrays don’t have a
Stringrepresentation that would, e.g. print all the elements. You need to print them explicitly:The output is an address:
However, the libs do supply the method
deepToStringfor this purpose, so this may also suit your purposes: