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]);
}

Output:

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 };
Arrays.sort(numbers);
for(int number : numbers) {
    System.out.print(number + " ");
}

Output:

1 5 9
Code in GitHub

Get the code for this tutorial using the links below.

Project Repo
Download code for this step
Main class for this step
Dependencies

This is a list of recommended tutorials or courses that might be useful before starting this one.

Contents
Welcome to the Course!
Course Introduction
Chapter 1 - Building Blocks
Quick introduction to Java Variables Classes And Objects Class Example - Defining a class Object Examples - Creating instances Java Application Example - Running our first app Accessing class members - The dot operator Packages - Organizing the code
Chapter 2 - Primitives and Operators
Primitives Arithmetic Operators Assignment Operator Unary Operators Equality and Relational Operators Conditional Operators
Chapter 3 - Statements and Control Flow
Expressions Statements If-Then Statement If-Then-Else Statement More If Statements Switch Statement While and Do-While Statements For Statement Branching Statements Exception Handling
Chapter 4 - Code Example
Example Project - A Simple Vending Machine Adding money Delivering Items Giving Change
Chapter 5 - Classes and Interfaces
Introduction Access Level Modifiers Class Declaration - Class, Methods and Fields Class Declaration - Constructors Inheritance Basics Inheritance - Constructors Inheritance - Methods and Fields Polymorphism Abstract Classes and Methods Interfaces Static Class Members Class Composition Final Classes and Class Members Generic Classes
Chapter 6 - Base Object Behaviors
Introduction Type Comparison Type Casting Object Equality - The Contract Object Equality - Common Pitfalls Object String Representation Garbage Collection Object Comparison Primitive Wrappers and Autoboxing
Chapter 7 - Data Structures
Introduction Arrays - Declaration and Creation Arrays - Basic Operations Core Collection Interfaces List and ArrayList - Basic Operations ArrayList Internals Introduction to Hash Tables Map and HashMap - Basic Operations Set and HashSet - Basic Operations
Chapter 8 - Anonymous classes and lambdas
Introduction Filtering a List Anonymous Classes Lambdas Built-in Functional Interfaces
Chapter 9 - Streams
Introduction Creating Streams Intermediate Operations Terminal Operations