0
0
JavaHow-ToBeginner · 3 min read

How to Print Array in Java: Simple Syntax and Examples

To print an array in Java, use Arrays.toString(array) for a readable string format or loop through the array elements and print each one. The Arrays.toString() method converts the array into a string that shows all elements inside square brackets.
📐

Syntax

Use Arrays.toString(array) to convert the array to a readable string. You must import java.util.Arrays. Alternatively, use a for loop to print each element individually.

  • Arrays.toString(array): Converts the whole array to a string.
  • for loop: Prints elements one by one.
java
import java.util.Arrays;

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

        // Or using a loop
        for (int num : numbers) {
            System.out.print(num + " ");
        }
    }
}
Output
[1, 2, 3, 4] 1 2 3 4
💻

Example

This example shows how to print an integer array using Arrays.toString() and a for-each loop.

java
import java.util.Arrays;

public class PrintArrayExample {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};

        // Print using Arrays.toString()
        System.out.println("Using Arrays.toString(): " + Arrays.toString(numbers));

        // Print using for-each loop
        System.out.print("Using for-each loop: ");
        for (int num : numbers) {
            System.out.print(num + " ");
        }
    }
}
Output
Using Arrays.toString(): [10, 20, 30, 40, 50] Using for-each loop: 10 20 30 40 50
⚠️

Common Pitfalls

A common mistake is printing the array directly with System.out.println(array), which prints a memory address instead of the elements. Always use Arrays.toString() or a loop to see the actual contents.

java
public class WrongPrint {
    public static void main(String[] args) {
        int[] arr = {5, 6, 7};

        // Wrong way: prints memory address
        System.out.println(arr);

        // Right way: prints elements
        System.out.println(java.util.Arrays.toString(arr));
    }
}
Output
[I@15db9742 [5, 6, 7]
📊

Quick Reference

Remember these quick tips to print arrays in Java:

  • Use Arrays.toString(array) for simple printing.
  • Use a for or for-each loop to customize output.
  • Do not print the array variable directly; it shows a memory address.

Key Takeaways

Use Arrays.toString(array) to print array elements as a readable string.
Avoid printing the array variable directly; it shows a memory address, not contents.
A for-each loop lets you print elements individually with custom formatting.
Always import java.util.Arrays to use Arrays.toString().