java

How to Print an Array in Java

In this tutorial, we are going to see different techniques to print an array in Java.
 

Example 1: Print an array using a For loop
public class Main {

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4};

        for (int i: arr) {
            System.out.println(i);
        }
    }
}

 
Output:

1
2
3
4
[st_adsense]  

Example 2: Print an array using the Array library
import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4};

        System.out.println(Arrays.toString(arr));
    }
}

Output:

[1, 2, 3, 4]

 

Example 3: Print a multidimensional array
import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        int[][] arr = {{1, 2, 3}, {3, 4, 5}, {6, 7}};

        System.out.println(Arrays.deepToString(arr));
    }
}

 
Output:

[[1, 2, 3], [3, 4, 5], [6, 7]]
[st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *