Skip to content

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.

Gopi Gorantala
Gopi Gorantala
3 min read

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

  1. Set the counter to 0.
  2. Run a loop of the first 100 values,
  3. And add each number to the counter.

Array of integers

  1. Set data equal to zero.
  2. Add the first number in the array to data.
  3. Repeat step 2 for the rest of the numbers in the array.
  4. 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:

  1. A record class for Book.
  2. 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.

Java Streams APIJava

Gopi Gorantala Twitter

Gopi is an engineering leader with 12+ of experience in full-stack development—a specialist in Java technology stack. He worked for multiple startups, the European govt, and FAANG in India and Europe.

Comments


Related Posts

Members Public

Differences Between JDK, JRE, and JVM?

Short answer JDK, JRE, and JVM are essential components of the Java platform, each serving a distinct purpose. Here are the key differences between them: 1. JDK (Java Development Kit): The JDK is used by developers to write, compile, and debug Java code. 2. JRE (Java Runtime Environment): End-users use

Members Public

Difference Between String and char[] in Java

Short answer Strings String is an object with many helpful methods. String class in Java's standard library is designed to handle text as a sequence of characters. A string of characters (string object) is non-modifiable or immutable in Java. Once you've created it, you cannot modify

Members Public

What is an Object class in Java?

Short answer Object class is the super class of every class you can create. In Java, a class extends another class using the keyword extends. If you don't have any other class to extend, that's fine. The compiler will make your class extend the Object class.