How to Print Arrays in Java | Java Program to Accept and Print Array Elements

CodeForHunger
2 min readJul 29, 2024

--

In this article, we are going to learn how to accept and print array elements in Java.

How to Print Arrays in Java:

To print array elements we first need to accept it from the user. In this post, we will learn how to accept array elements from the user dynamically and print them on the output screen. Simple Java program to insert elements in the array.

How to Print Arrays in Java | Java Program to Accept and Print Array Elements, How to print arrays in java, arrays in java

We can print array elements using any type of loop like :

Step-by-Step Logic of the Given Program :

We can take array input from the user using the method of the Scanner class.

1. Accept array elements from the user one by one using a simple for loop:

for(int i=0;i<5;i++) { 
a[i]=sc.nextInt();
}

2. Print Elements using for loop In this program I used Enhanced for loop to print array elements:

for(int e:a) { 
System.out.print(e+" ");
}

but, you can also use simple for loop to print array elements like:

for(int i=0;i<5;i++) { 
System.out.print(a[i]+" ");
}

Simple Array Program to Accept and Print Array Elements:

import java.util.Scanner;

public class SimpleArrayExample {

public static void main(String[] args) {
//Declaration and instantiation
int a[] = new int[5];
Scanner sc = new Scanner(System.in);
//Accepting elements using simple for loop
System.out.println("ENTER THE ELEMENTS: ");
for(int i=0;i<5;i++) {
a[i]=sc.nextInt();
}
System.out.println("ELEMENTS IN ARRAY ARE: ");
//printing elements using Enhanced for loop(for-each loop)
for(int e:a) {
System.out.print(e+" ");
}
}
}

Same above Program using a while loop:

In the above program, we have used for loop to store and print array elements. So, In this program, we will use a while loop to store and print array elements.

import java.util.Scanner;

public class SimpleArrayExample {

public static void main(String[] args) {
//Declaration and instantiation
int a[] = new int[5];
Scanner sc = new Scanner(System.in);
//Accepting elements using while loop
System.out.println("ENTER THE ELEMENTS: ");
int i=0;
while(i<5) {
a[i]=sc.nextInt();
i++;
}
System.out.println("ELEMENTS IN ARRAY ARE: ");
//printing elements using while loop
int j=0;
while(j<5) {
System.out.print(a[j]+" ");
j++;
}
}
}

OUTPUT:

ENTER THE ELEMENTS:

5

3

8

2

1

ELEMENTS IN ARRAY ARE:

5 3 8 2 1

Originally published at https://codeforhunger.blogspot.com.

--

--

CodeForHunger

Here, I will share tips & tricks to learn programming languages, Learn C and Java with lot of exercises, coding examples & interview questions. Follow for more.