When learning Java, it’s easy to understand syntax by looking at basic exercises. But to really remember how things work, it helps to connect programming to the real world. That’s what this article is about.
Here you’ll find realistic examples for each of the main ways to loop through arrays:
for
loopwhile
loop- enhanced
for-each
loop - Stream API
Each example will show how arrays and loops can be used to solve simple but meaningful problems. No theory — just situations that make sense in everyday life or common software tasks.
1. Using a for loop: Solar Panel Monitoring
Scenario: You have 5 solar panels and need to check if any of them are underperforming.
public class SolarPanelMonitor {
public static void main(String[] args) {
// Array holding the light level (in watts per square meter) for each solar panel.
//These values might come from light level indicators.
int[] lightLevels = {950, 720, 980, 400, 890};
// Light level threshold below which a panel is considered underperforming.
//This value serves as the standard for performance comparison.
int threshold = 800;
// Variable to store the total light level, used to calculate the average later.
//This value will increase during the loop as light levels are summed up.
int total = 0;
// Variable to keep track of the lowest light level found so far.
//This value will be updated during the loop until the minimum is found.
int minValue = lightLevels[0];
// Variable to remember which panel has the lowest light level (index in the array)
int minIndex = 0;
// Loop through each panel by its index
for (int i = 0; i < lightLevels.length; i++) {
/* Print the light level of the panel currently being analyzed by
the program as it iterates through each element of the array.
The program will print 5 lines in total — one for each of the 5 panels.*/
/* lightLevels[i] accesses the value at the current index i.
Here, i is a variable representing the index of the current element in the array.*/
System.out.println("Panel " + i + " light level: " + lightLevels[i]);
/* Check if the light level is below the threshold
This compares the current panel's light level with
the threshold value defined earlier as a reference point.*/
if (lightLevels[i] < threshold) {
System.out.println("→ Panel " + i + " is underperforming. Check for dirt or shade.");
}
// Add the current light level to the total for averaging.
/* The += operator adds the current value to the total variable,
gradually summing up all values in the array.*/
total += lightLevels[i];
// Check if the current panel has the lowest light level so far
if (lightLevels[i] < minValue) {
minValue = lightLevels[i]; // Update the lowest value
minIndex = i; // Remember the index of the panel
}
}
// Calculate the average light level across all panels
double average = (double) total / lightLevels.length;
// Print the average light level
System.out.println("\nAverage light level: " + average);
// Print which panel had the lowest light level and what that value was
System.out.println("Panel " + minIndex + " has the lowest light level: " + minValue);
}
}
2. Reacting to Critical Values in a Stream of Sensor Data (with while
loop)
Scenario:
This program simulates a heating control system that scans incoming temperature data from multiple sensors.
The simulation block generates a list of temperature readings from 300 to 500 sensors. One of the values is always set to -49°C
to represent a critical condition.
We use a while
loop in this example because we don’t know in advance how many sensors will need to be checked. This could happen in real-world situations where:
- Sensors become active based on specific logic (e.g., only sensors in cold zones report values);
- Data arrives dynamically from remote devices or is streamed in small batches;
- The system scans values one by one and stops processing as soon as a critical temperature is detected.
The loop continues until it finds the temperature -49°C
, which triggers a warning that the heating system should be turned on.
import java.util.Random;
public class HeatingSystemSimulator {
public static void main(String[] args) {
// ----------------------------- //
// Simulation block (not for study — just for demonstration)
// Generates input data that mimics sensor readings
// ----------------------------- //
Random random = new Random();
int size = 300 + random.nextInt(201); // Generates number between 300 and 500
int[] temperatures = new int[size];
// Fill the array with random values from -50 to 50
for (int i = 0; i < size; i++) {
temperatures[i] = -50 + random.nextInt(101); // [-50, +50]
}
// Inject the critical temperature (-49) at a random index
int criticalIndex = random.nextInt(size);
temperatures[criticalIndex] = -49;
// ----------------------------- //
// Processing part: real logic starts here
// ----------------------------- //
int i = 0; // Index variable to loop through the array
boolean warningIssued = false; // Flag to indicate whether warning was triggered
// Loop through each temperature reading until the critical value is found
while (i < temperatures.length) {
System.out.println("Temp at sensor " + i + ": " + temperatures[i]);
// Check if the current temperature equals -49
if (temperatures[i] == -49) {
// If found, print the warning and stop checking further
System.out.println("Temperature too low - heating should be turned on.");
warningIssued = true;
break; // Exit the loop
}
// Move to the next temperature reading
i++;
}
// Если критическая температура не найдена в массиве
if (!warningIssued) {
System.out.println("All temperatures are within acceptable range.");
}
}
}
3. Using a for-each loop: Counting Free Parking Spaces
Scenario:
Imagine a parking lot with a large number of spaces. Each parking slot is either occupied (true
) or free (false
). The system scans the list of slots and counts how many are currently free.
In this simulation, we randomly generate between 20 and 50 parking slots. Around 30% of them are marked as free to reflect a typical real-world situation.
We use a for-each
loop because:
- We don’t need to know the index of each slot.
- We only care about the value — whether it’s free or not.
for-each
makes the loop simpler and easier to read.
The system goes through all the values and prints the total number of available spaces.
Where does the parking data come from?

In real-world parking systems, each slot is usually equipped with a sensor — for example:
- Ultrasonic sensors that detect whether a car is present;
- Infrared or magnetic sensors that react to the vehicle’s body or movement;
- Computer vision systems that analyze camera footage and decide if a space is occupied;
- Entry/booking systems that update a central database when a car checks in.
These systems convert the real-world signals into simple digital data — typically a true
or false
value for each parking space.
This data is then used by the parking management software to track occupancy in real time.
import java.util.Random;
public class ParkingSlotCounter {
public static void main(String[] args) {
// ----------------------------- //
// Simulation block (not for study — just for demonstration)
// Generates a random parking situation with 20 to 50 parking slots
// true = occupied, false = free
// ----------------------------- //
Random random = new Random();
int size = 20 + random.nextInt(31); // Size between 20 and 50
boolean[] parkingSlots = new boolean[size];
/* Fill array with random occupancy: 70% chance a slot is occupied (true),
30% free (false)*/
for (int i = 0; i < size; i++) {
parkingSlots[i] = random.nextDouble() < 0.7; // true means occupied
}
// ----------------------------- //
// Processing block using for-each
// ----------------------------- //
int freeSlots = 0; // Counter for available (free) parking spots
// Loop through all parking slots using a for-each loop
for (boolean isOccupied : parkingSlots) {
// If the slot is not occupied, count it as free
if (!isOccupied) {
freeSlots++;
}
}
// Print total number of available parking slots
System.out.println("Total free parking slots: " + freeSlots + " out of " + parkingSlots.length);
}
}
4. Using Stream API: Two Ways to Loop Through Arrays Using Stream API
When working with arrays in Java, Stream API offers two common approaches depending on what you need:
just the values, or both the values and their positions (indexes).
1. If you only need the values
Use Arrays.stream(array)
This is useful when you want to process each element but don’t care about where it is.
Example: Show all temperatures above 40°C
Scenario 1: Save and Display High Temperatures
Context:
You have a list of temperature readings from various sensors. Your task is to identify all values greater than 40°C, store them for potential further use (e.g. analysis or alerting), and display them to the user. You’re only interested in the temperature values, not in which sensor provided them.
Data source:
In this example, the input data is hardcoded:
int[] temperatures = {35, 42, 38, 47, 31};
But in real-life applications, such data would typically be fetched from sensors, logs, or API responses.
Use case:
You want to:
- Extract all temperatures over 40°C.
- Store them in a separate array (
hotTemps
) for reuse. - Print each high temperature with a short alert message.
- Show how many high values were found.
This is a classic example of value-based filtering and collection, where you’re not transforming or analyzing all data — just pulling out specific results.
Suitable loop type:
Use Arrays.stream()
with .filter()
and .toArray()
— perfect for working only with values and creating a new result array.
int[] temperatures = {35, 42, 38, 47, 31};
int[] hotTemps = Arrays.stream(temperatures)
.filter(temp -> temp > 40)
.toArray();
System.out.println("Found " + hotTemps.length + " high temperatures:");
for (int temp : hotTemps) {
System.out.println("Too hot: " + temp + "°C");
}
Explanation:
Arrays.stream(temperatures)
— turns the array into a stream of values..filter(temp -> temp > 40)
— keeps only the values above 40°C..toArray()
— collects the result back into anint[]
array (hotTemps
).hotTemps.length
— tells you how many values matched the condition.for (int temp : hotTemps)
— you loop through and print the filtered values.
This method is clean and efficient when:
- You don’t care where the values came from.
- You might use the filtered array again later (not just for printing).
- You want readable and concise code.
What is .filter()
?
The .filter()
method is part of the Java Stream API. It allows you to choose only the values that meet a condition.
In this case, it keeps only temperatures above 40°C.
- It accepts a predicate (a condition that returns true or false).
- It does not change the original data — it just filters the stream.
- Defined in
java.util.stream.Stream
and available inIntStream
,DoubleStream
, etc.
This is similar to a regular for-each
loop:
int[] temperatures = {35, 42, 38, 47, 31};
// Step 1: Print all temperatures above 40°C
for (int t : temperatures) {
if (t > 40) {
System.out.println("Too hot: " + t + "°C");
}
}
// Step 2: Count how many temperatures are above 40°C
int count = 0;
for (int t : temperatures) {
if (t > 40) {
count++;
}
}
// Step 3: Create a new array to store high temperatures
int[] hotTemps = new int[count];
int index = 0;
for (int t : temperatures) {
if (t > 40) {
hotTemps[index] = t;
index++;
}
}
// Step 4: Print how many high temperatures were found
System.out.println("Found " + hotTemps.length + " high temperatures:");
2. If you also need the index
Use IntStream.range(0, array.length)
and access array[i]
This approach gives you both the index and the value by manually referring to array[i]
.
Example: Show temperatures above 40°C along with their positions
Scenario 2: Find Overheating Positions
Context:
You have a sequence of temperature readings, and you want to identify not just the values above a critical threshold, but also where in the sequence they occurred. For example, in a system with multiple sensors or time-indexed data, knowing the position (index) of the overheating value is essential for troubleshooting.
Data source:
Again, in this example, we use hardcoded input:
int[] temperatures = {35, 42, 38, 47, 31};
In a real-world application, these values might come from a sensor array, a time-series database, or a data stream.
Use case:
List all temperatures over 40°C, along with their corresponding indexes.
Suitable loop type:
Using IntStream.range()
gives access to both the index and the value through temperatures[i]
, making this approach clean and expressive.
Code example:
int[] temperatures = {35, 42, 38, 47, 31};
IntStream.range(0, temperatures.length)
.filter(i -> temperatures[i] > 40)
.forEach(i -> System.out.println("Too hot at index " + i + ": " + temperatures[i] + "°C"));
Summary:
What you need | Use this |
---|---|
Just the values | Arrays.stream(array) |
Values with indexes | IntStream.range(...) + array[i] |
Both styles are valid — choose the one that fits your task.
Stream API helps make your code shorter, clearer, and easier to maintain.
Conclusion
Each of these examples takes something abstract — like an array — and gives it a purpose. Once you see how code applies to real things, it gets easier (and more fun) to practice.
If you haven’t yet reviewed how to loop through arrays in Java, go check out the Looping Through Arrays in Java for a full overview of the syntax and logic.
Happy coding!