Java Program to Print Elements of an Array

Share

In Java, an array is an object that is capable of storing a fixed number of elements having similar types. It uses an index in order to directly access a particular item.

There are various ways to print an array :

  1. Simply, iterating through a loop
  2. Using Arrays class method
  3. Using advance for loop

The program initializes and prints all the elements of an array.

Print elements of an array using Loop

Program:

import java.util.Scanner;
public class Array {
public static void main(String[] args) {
Scanner ed=new Scanner(System.in);
int[] a=new int[5];
int i;
System.out.println("Please Enter An Array");
for(i=0;i<5;i++)
{
a[i]=ed.nextInt();
}
System.out.println("Entered Array:-");
for(i=0;i<5;i++)
{
System.out.println(a[i]);
}
} 
}

 

Output:

Print elements of an array using Advance For loop

Program: 

import java.util.Scanner;

public class ArrayPrint {
    public static void main(String[] args) {
        Scanner ed = new Scanner(System.in);
        int[] arr = new int[5];
        int i;
        System.out.println("Please Enter An Array");
        for (i = 0; i < 5; i++) {
            arr[i] = ed.nextInt();
        }
        System.out.println("Entered Array:-");
      for(int item : arr){
          System.out.println(item);
      }
    }
}

Output: 

Please Enter An Array
32
54
32
5
67
Entered Array:-
32
54
32
5
67

Print elements of an array Using Arrays.toString()

Program:

import java.util.Arrays;
import java.util.Scanner;

public class ArrayPrint {
    public static void main(String[] args) {
        Scanner ed = new Scanner(System.in);
        int[] arr = new int[5];
        int i;
        System.out.println("Please Enter An Array");
        for (i = 0; i < 5; i++) {
            arr[i] = ed.nextInt();
        }
        System.out.println("Entered Array:-");
        System.out.println(Arrays.toString(arr));
    }
}

Output:

Please Enter An Array
45
76
43
2
45
Entered Array:-
[45, 76, 43, 2, 45]

This post was last modified on September 26, 2020

Sandeep Verma

Published by
Sandeep Verma
Tags: elements Elements of an Array java java program Java Program to Print the Elements of an Array program