What is Imperative Programming? With Examples
In this lesson, you will learn imperative programming and the steps to achieve it. You will also be introduced to some real-world use cases for easy understanding.
Table of Contents
Introduction to imperative programming
Imperative programming is a type of software design that employs statements to alter the program's state.
Object-Oriented programming is an imperative style of programming.
- In imperative, we treat values as buckets. So the value can be modified in the application at any time.
- Variables declared hold some value and change at some point in the program. Think of POJO class variables with setters. Modification of variable value is allowed.
- In loops, we iterate through each value, and before processing each item, we update the garbage variable we initialized in the loop.
From the above understanding, we can say imperative programming embraces object mutability.
Imperative is step-by-step instructions on how to achieve an objective. It focuses on how to do things.
Illustrations
Simple counter
- Set the
counter
to0
. - Run a loop of the first
100
values, - And add each number to the
counter
.
Array of integers
- Set
data
equal to zero. - Add the first number in the array to
data.
- Repeat step 2 for the rest of the numbers in the array.
- Divided
data
by the length of the array.
Examples
Remove duplicates
Removing duplicate entries from a collection is a perfect example of an imperative approach, as it deals with loops mutating the garbage variable we create inside the loop.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Duplicates {
public static void main(String[] args) {
List<Integer> values = Arrays.asList(1, 1, 2, 2, 3, 4, 5, 6, 7, 7, 8);
List<Integer> uniqueValues = new ArrayList<>();
// in below, `value` variable is changed/updated for each iteration (imperative way).
for (int value : values) {
if (!uniqueValues.contains(value)) {
uniqueValues.add(value);
}
}
System.out.println("After removing duplicates: " + uniqueValues);
}
}
What are we doing above? let's see each of the lines we've written above in action.
List<Integer> values = Arrays.asList(1, 1, 2, 2, 3, 4, 5, 6, 7, 7, 8);
We have a list of integer
values stored in List<Integer>
for (int value : values) {
if (!uniqueValues.contains(value)) {
uniqueValues.add(value);
}
}
Simple for-loop to iterate elements
Line 2 contains a if
condition that ignores an element if it's already available in the list.
Line 3, we are just adding elements that pass the if
condition.
Have you noticed anything? We are mutating/changing variable value
, that are holding an element and updating the state from one to another. This is imperative in a nutshell.
List of objects
We dealt with variables that are holding data. The following example re-iterates the same concept but for Java objects.
This is yet another simple example containing:
- A
record
class forBook
. - An execution class that contains the
main
method, runs the application to perform the imperative approach.
import java.util.Arrays;
import java.util.List;
public record Book(
String title,
String author,
Integer year,
Integer copiesSold,
Double rating,
Double costInEuros) {
// statements
public static List<Book> BOOKS =
Arrays.asList(
new Book("Don Quixote", "Miguel de Cervantes", 1605, 500, 3.9, 9.99),
new Book("A Tale of Two Cities", "Charles Dickens", 1859, 200, 3.9, 10.0),
new Book("The Lord of the Rings", "J.R.R. Tolkien", 2001, 150, 4.0, 12.50),
new Book("The Little Prince", "Antoine de Saint-Exupery", 2016, 142, 4.4, 5.0),
new Book("The Dream of the Red Chamber", "Cao Xueqin", 1791, 100, 4.2, 10.0));
}
import java.util.List;
import src.dev.ggorantala.model.Book;
public class ListObjects {
public static void main(String[] args) {
List<Book> imperativeApproach = Book.BOOKS;
for (Book book : imperativeApproach) {
if (book.costInEuros() >= 5) {
System.out.println(book);
}
}
}
}
/*
Outputs:
Book[title=Don Quixote, author=Miguel de Cervantes, year=1605, copiesSold=500, rating=3.9, costInEuros=9.99]
Book[title=A Tale of Two Cities, author=Charles Dickens, year=1859, copiesSold=200, rating=3.9, costInEuros=10.0]
Book[title=The Lord of the Rings, author=J.R.R. Tolkien, year=2001, copiesSold=150, rating=4.0, costInEuros=12.5]
Book[title=The Little Prince, author=Antoine de Saint-Exupery, year=2016, copiesSold=142, rating=4.4, costInEuros=5.0]
Book[title=The Dream of the Red Chamber, author=Cao Xueqin, year=1791, copiesSold=100, rating=4.2, costInEuros=10.0]
*/
In the above execution class, we have a list of Book
objects stored in imperativeApproach
variable.
for (Book book : imperativeApproach) {
if (book.costInEuros() >= 5) {
System.out.println(book);
}
}
Simple for-loop to iterate all the Book
objects. The if
condition filters the books if their cost is equal to or greater than 5
. Any Book
item that passes this condition is printed on the console.
Have you noticed anything? The same problem as above, we are mutating/changing variable book
inside the for-loop, that's holding the Book
object and updating the state from one to another.
This is an imperative way of filtering data and mutating garbage variable book
inside the loop.
Gopi Gorantala Newsletter
Join the newsletter to receive the latest updates in your inbox.