Java ProgramsArraysCreate and Print Array

Create and Print Array in Java

beginner·  Arrays  ·  Array

Problem

An array is a fixed-size, ordered collection of values of the same type, each accessible by its index.

Declare an array of integers and print every element it holds.

Input
{5, 12, 8, 21, 3}
Output
5 12 8 21 3

Java Program

Java
public class CreateAndPrintArray { public static void main(String[] args) { int[] arr = {5, 12, 8, 21, 3}; for (int num : arr) { System.out.print(num + " "); // space-separated, all on one line } } }

Output

5 12 8 21 3

Core Logic

Declaring the array with an initializer list creates and fills it in one step, and a for-each loop then visits every element to print it.

How It Works
  1. 1int[] arr = {5, 12, 8, 21, 3}; declares the array and fills it with five values in a single statement.
  2. 2A for-each loop visits each element of arr in order, without needing a separate index variable.
  3. 3System.out.print(num + " ") prints each value followed by a space, keeping every element on the same line.
For {5, 12, 8, 21, 3}, the loop prints each value in turn, producing 5 12 8 21 3.
💡

Key Point: An array's size is fixed the moment it's created — arr.length is 5 for the rest of the program, and no more elements can be added or removed.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

Why: Each element is visited once to print it, and no extra storage is used beyond the array itself.

Key Concepts

array literalfor-each looparray index

Approach 2: Using Arrays.toString()

Java
import java.util.Arrays; public class CreateAndPrintArrayBuiltin { public static void main(String[] args) { int[] arr = {5, 12, 8, 21, 3}; // Arrays.toString() formats the whole array in one call System.out.println(Arrays.toString(arr)); } }

Output

[5, 12, 8, 21, 3]

Core Logic

In real code, there's no reason to loop manually just to print an array — Arrays.toString() already formats the whole thing in one call.

How It Works
  1. 1Arrays.toString(arr) takes the array and returns a single formatted String.
  2. 2The format wraps every element in square brackets, separated by commas.
  3. 3No explicit loop is needed in your own code.
Arrays.toString(new int[]{5, 12, 8, 21, 3}) returns "[5, 12, 8, 21, 3]" in a single call.
💡

Key Point: This is the version to actually use for debugging or logging — the manual loop exists only to show how printing an array works element by element.

Complexity
Time Complexity: O(n)Space Complexity: O(n)

Why: Arrays.toString() still visits every element once internally, but builds an entirely new formatted String to return.

Key Concepts

Arrays.toString()

Related Programs