Java Program to Print an Array

Java Program to Print an Array

What is an Array in Java ?

In Java, an array is a collection of similar type of elements, which can be of primitive data types like int, char, double, float, etc., or reference data types like objects or other arrays. An array is a container object that holds a fixed number of elements, which are stored in contiguous memory locations.

Ways to Print an Array in Java :

Syntax :

int[] myArray = {1, 2, 3, 4, 5};
for (int num : myArray) {
    System.out.println(num);
}

Syntax :

int[] myArray = {1, 2, 3, 4, 5};
for (int num = 0; num < myArray.length ; num++) {
    System.out.println(myArray[num]);
}

Syntax :

int[] myArray = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(myArray));

Syntax :

int[][] myArray = {{1, 2}, {3, 4}, {5, 6}};
System.out.println(Arrays.deepToString(myArray));

Syntax :

int[] myArray = {1, 2, 3, 4, 5};
Arrays.stream(myArray).forEach(System.out::println);

Example 1 : 

Run
import java.util.Arrays;

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

        // Using for loop:
        System.out.println("Using for loop:");
        for (int i = 0; i < myArray.length; i++) {
            System.out.println(myArray[i]);
        }

        // Using for-each loop:
        System.out.println("Using for-each loop:");
        for (int num : myArray) {
            System.out.println(num);
        }

        // Using Arrays.toString() method:
        System.out.println("Using Arrays.toString() method:");
        System.out.println(Arrays.toString(myArray));
    }
}

Output :

Using for loop:
1
2
3
4
5
Using for-each loop:
1
2
3
4
5
Using Arrays.toString() method:
[1, 2, 3, 4, 5]
  

Example 2 : 

Run
import java.util.Arrays;

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

Output :

[[1, 2], [3, 4], [5, 6]]

Example 3 : 

Run
import java.util.Arrays;

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

Output :

1
2
3
4
5

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription