Chapter 7 - Java for Beginners Course

Arrays - Basic Operations

In the previous section we introduced the concept of arrays in Java, and saw how to define and create an array and how to access the elements in the array.

In this section we’ll show a few operations that are commonly done with arrays. The examples we’ll show below can be performed/coded in different ways. Here we’re showing a way of doing things. We’ll cover other approaches in later sections and in other courses.

Iterate over the elements

One of the most common operations is to go over all elements in the array/data structure. This is done for different reasons, for example, you might want to print out the contents of an array.

One way of doing this is using a for-loop:

In the example code run the JavaArrayOperationsApp
String[] words = { "An", "example", "sentence" };
for (int i = 0; i < words.length; i++) {
    System.out.println("Word: " + words[i]);


Word: An
Word: example
Word: sentence

In this case, we’re using a standard for loop where our loop variable i iterates from 0 until the end of the array
(i < words.length).

Iterating over a data structure is required for many things, including:

  • Checking if an element exists or not (and where): for example, is the word "sentence" in the array?

  • Filter elements: for example, find all words that have more than 4 characters

  • Find the minimum/maximum/average of a collection

  • Etc.

Enhanced-for loop

The approach above to iterating the elements of an array used to be the standard several years ago. With new versions of Java, new ways of iterating and operating over data structures have been developed, one of them being the enhanced-for loop.

Its syntax is:

for (Type element : collection) {
	// ...

Given a collection of objects (it could be an array or one of the data structures we’ll introduce in the next sections), we’re telling Java that we want to iterate one by one. The element variable will be the element we’re processing on each iteration.

This means that we can re-write our first example as follows:

String[] words = { "An", "example", "sentence" };
for (String word : words) {
    System.out.println("Word: " + word);

And we’d get the same output.

Since Java 8, Streams are a new way of operating on data in a more functional programming way. We won’t be covering them in this chapter as it requires us to introduce lambdas which will be covered later.

Sorting an array

In certain cases, we might need to sort our data, either because we need to present it to the user in a specific order, or because for efficiency we need to ensure it is sorted before we process it further.

There are multiple sorting algorithms available, but one of the most common approaches is to use the utility static methods in the Arrays class, one of them being Arrays.sort:

int[] numbers = { 9, 5, 1 };
for(int number : numbers) {
    System.out.print(number + " ");


1 5 9