Create and Print Array in Java
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.
Java Program
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
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.
- 1
int[] arr = {5, 12, 8, 21, 3};declares the array and fills it with five values in a single statement. - 2A for-each loop visits each element of
arrin order, without needing a separate index variable. - 3
System.out.print(num + " ")prints each value followed by a space, keeping every element on the same line.
{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.
Why: Each element is visited once to print it, and no extra storage is used beyond the array itself.
Key Concepts
Approach 2: Using Arrays.toString()
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
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.
- 1
Arrays.toString(arr)takes the array and returns a single formattedString. - 2The format wraps every element in square brackets, separated by commas.
- 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.
Why: Arrays.toString() still visits every element once internally, but builds an entirely new formatted String to return.