Back to Java
2026-01-236 min read

Example 2: Printing Array Elements Using for Loop (Java)

Learn Example 2: Printing Array Elements Using for Loop (Java) step by step with clear examples and exercises.

Title: Printing Array Elements Using for Loop (Java)

Why This Matters

In this lesson, we delve into the essential skill of printing array elements using a for loop in Java. Mastering this technique is crucial when working with arrays and will help you tackle real-world problems involving large datasets or user inputs. By understanding how to print array elements using a for loop, you will be well-equipped to solve complex programming tasks.

Prerequisites

To fully grasp this lesson, it is essential that you have a solid understanding of the following topics:

  1. Java fundamentals (variables, data types, operators)
  2. Arrays in Java (declaration, initialization, and accessing elements)
  3. Control structures (if, else, and switch statements)
  4. Basic loop structure (while and do-while)
  5. Understanding of indexes and arrays' zero-based indexing system
  6. Exception handling in Java (particularly ArrayIndexOutOfBoundsException)
  7. Data types and their properties (e.g., primitive vs. reference)
  8. Basic string manipulation (concatenation, length, substring)
  9. User input using the Scanner class

Core Concept

To print array elements using a for loop in Java, follow these steps:

  1. Declare and initialize an array with any desired data type.
  2. Use a for loop to iterate through the array's indexes (starting at 0).
  3. Access each element by its index within the loop body.
  4. Print the element using the System.out.println() method or concatenation for strings.
  5. Handle any potential exceptions, such as ArrayIndexOutOfBoundsException.
  6. For string arrays, you may need to check if an element is empty (e.g., two spaces) before printing it.

Here's an example of printing the elements of a simple integer array:

public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5}; // Declare and initialize an integer array

try {
for (int i = 0; i < arr.length; i++) { // Iterate through the array using a for loop
System.out.println(arr[i]); // Print each element
}
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Error: Index out of bounds.");
}
}
}

In this example, we declare an integer array arr with five elements and initialize it with the values 1, 2, 3, 4, and 5. We then use a for loop to iterate through the indexes of the array (0 to 4) and print each element using the System.out.println() method. To handle potential exceptions like ArrayIndexOutOfBoundsException, we wrap the loop body in a try-catch block.

Worked Example

Let's explore a more complex example that involves printing the elements of a string array and handling an empty array case:

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Create a Scanner object for user input

System.out.print("Enter the number of elements in your array: ");
int numElements = scanner.nextInt(); // Get the number of elements from the user

String[] arr = new String[numElements]; // Declare and initialize a string array with the specified size

for (int i = 0; i < numElements; i++) { // Iterate through the array using a for loop
System.out.print("Enter element " + (i + 1) + ": ");
arr[i] = scanner.next(); // Get user input and store it in the current index of the array
}

for (int i = 0; i < arr.length; i++) { // Iterate through the array using a for loop
if (arr[i].equals("")) { // Check if the current element is empty (represented by two spaces)
System.out.println("Empty"); // Print "Empty" if the element is empty
} else {
System.out.println(arr[i]); // Print the non-empty elements
}
}
}
}

In this example, we create a Scanner object to get user input for the number of elements in the array and their values. We then declare a string array with the specified size and use two nested loops: one to get user input and store it in the array, and another to print the elements using a for loop. To handle cases where an element is empty (represented by two spaces), we check whether it's equal to an empty string using the equals() method. If the current element is empty, we print "Empty"; otherwise, we print the non-empty elements.

Common Mistakes

  1. Forgetting to initialize the array: Make sure you declare and initialize your array before trying to access its elements.
  2. Incorrect loop condition: The loop should iterate from 0 to arr.length - 1 instead of just arr.length.
  3. Accessing out-of-bounds indexes: Be careful not to access indexes that are greater than or equal to the length of the array. This will result in a ArrayIndexOutOfBoundsException.
  4. Not handling empty elements: If you're working with user inputs, make sure to handle cases where an empty string is provided.
  5. Misunderstanding the loop variable: Remember that the loop variable (e.g., i) represents the current index being processed in the array.
  6. Forgetting exception handling: It's important to handle potential exceptions like ArrayIndexOutOfBoundsException when working with arrays.
  7. Not checking for empty elements: When working with user inputs, it's crucial to check if an element is empty before printing it or performing further operations on it.
  8. Incorrectly handling data types: Make sure to handle different data types (e.g., integers, strings) appropriately when iterating through arrays and printing their elements.

Practice Questions

  1. Write a Java program that prints the elements of an integer array using a for loop. The array should be initialized with the values 10, 20, 30, 40, and 50.
  2. Modify the worked example to handle arrays with more than five elements.
  3. Write a Java program that takes user input for an integer array and prints its elements using a for loop. The program should also check if the user has entered valid integers.
  4. Create a Java program that initializes a string array with the names of your favorite fruits and prints them using a for loop.
  5. Write a Java program that reads an integer array from a file, sorts it using a sorting algorithm (e.g., bubble sort), and prints the sorted array using a for loop.

Subheadings under Common Mistakes:

  • Handling empty arrays
  • Accessing out-of-bounds indexes
  • Exception handling best practices
  • Handling different data types
  • Checking for empty elements in user input

FAQ

  1. Why do we use 0 as the starting index for arrays in Java?
  • Arrays in Java are zero-indexed, meaning the first element is at index 0. This convention simplifies array access and makes it consistent with other programming languages like C and Python.
  1. Can I use a for loop to iterate through an array in reverse order?
  • Yes! To iterate through an array in reverse order, you can modify the loop condition to start at arr.length - 1 and decrease the loop variable by one on each iteration.
  1. What happens if I try to access an index that is out of bounds for my array?
  • If you try to access an index that is out of bounds for your array, a ArrayIndexOutOfBoundsException will be thrown. This exception indicates that the program has attempted to access an element outside the valid range of the array.
  1. What are some common uses of arrays in programming?
  • Arrays are used extensively in programming for various purposes such as storing collections of data, implementing dynamic memory allocation, and solving problems involving repetition or iteration.
  1. How can I handle empty elements when iterating through an array with a for loop?
  • To handle empty elements, you can check if the current element is null or empty using the isEmpty() method (for strings) or by checking for specific conditions based on your data type. If an empty element is found, you can choose to print a custom message or skip it during iteration.
Example 2: Printing Array Elements Using for Loop (Java) | Java | XQA Learn