Write a Java Program to Print an Array

Printing an array is a common operation in Java programming.

An array is a collection of elements of the same data type, arranged in a contiguous memory location.

In Java, arrays are objects, and they can be printed using various methods.


To print an array in Java, we can use a loop or a built-in method.

Here are the steps to print an array using a loop:

  1. Declare an array variable and initialize it with values.
  2. Use a loop to iterate over the array elements.
  3. Print each element of the array using the System.out.println() method.

Here is an example Java program that prints an array using a loop:

public class PrintArray {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}

In the above example, we have declared an integer array named arr and initialized it with the values {1, 2, 3, 4, 5}.

We have used a for loop to iterate over the array elements and printed each element using the System.out.println() method.

Another way to print an array in Java is to use the Arrays.toString() method.

Here is an example Java program that prints an array using the Arrays.toString() method:

import java.util.Arrays;

public class PrintArray {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        System.out.println(Arrays.toString(arr));
    }
}

In the above example, we have imported the java.util.Arrays class and used its toString() method to print the array arr.


In conclusion, printing an array in Java is a simple operation that can be done using loops or built-in methods.

By using these methods, we can easily print the contents of an array to the console.