Print an Array in Java

Exercise:

Write a Java Program to print an array.

1.Print using for loop

Click Here to View the Solution!
public class PrintArray {
  public static void main(String[] args) {
         int[] array = {1, 2, 3, 4, 5,6,7,8};
  
         for (int element: array) {
             System.out.println(element);
         }
     }
 } 
Click Here to View the Output!
 1
 2
 3
 4
 5
 6
 7
 8
Click Here to View the Explanation!
  • This program is used for printing all the elements of an array by using a for loop.
  • Firstly, an integer array is initialized which contains 8 integers, that are the elements of the array.
  • The program uses a for-each loop that is used for iterating between the elements of an array.
  • The loop is able to access all the elements existing in the array and print an element using the println() statement in every iteration.

2.Print using standard library Arrays

Click Here to View the Solution!
import java.util.Arrays;
public class PrintArray {
 
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5,6,7,8};
        System.out.println(Arrays.toString(array));
    }
} 
Click Here to View the Output!
[1, 2, 3, 4, 5, 6, 7, 8]
Click Here to View the Explanation!
  • This program is used for printing all the elements of an array by using a standard library of Arrays.
  • Firstly, an integer array is initialized which contains 8 integers, that are the elements of the array.
  • Like the above program, this program is used for printing the array elements however, instead of using a for loop, this program utilizes a function of a standard library of Arrays, Arrays.toString().
  • This function allows the printing of the elements without using any extra lines and gives a clear output in a single line.

3.Print a Multi-dimensional Array

Click Here to View the Solution!
import java.util.Arrays;
public class Array {
 
    public static void main(String[] args) {
        int[][] array = {{1, 3}, {2, 4}, {5, 6, 7,8}, {9,10}};
        System.out.println(Arrays.deepToString(array));
    }
} 
Click Here to View the Output!
[[1, 3], [2, 4], [5, 6, 7, 8], [9, 10]]
Click Here to View the Explanation!
  • This program is used for printing a multidimensional array by using a function of the library Arrays.
  • Like the above program, which used a standard library function (Arrays.toString()), this program needs to use another function, since this one will just print the addresses of the elements in a multidimensional array.
  • Initially, a two-dimensional array that is an array containing another array (nested array).
  • In order to print the integer elements of this array, another Array library function (Arrays.deeoToString()).
  • This function iterates between all the elements of the two-dimensional array and prints each integer elements.
  • The Arrays.deepToString function is also used to print the elements of a 3-dimensional array.