Imperative VS Declarative Programming Part 1

This tutorial aims to deepen your understanding of the Imperative and Declarative styles of programming in Java. You will delve into the differences between the Imperative and Declarative styles of programming in Java through this tutorial.

By the end of this tutorial, you will have a stronger grasp of the Imperative and Declarative styles of programming in Java.

Part two of this tutorial you can read here: “Imperative VS Declarative Programming Part 2“.

Imperative Style of Programming

The Imperative style emphasizes getting the desired outcome and performing actions by changing an object’s state. We mostly work with objects that can be altered.

It lays out a step-by-step process for executing tasks and requires us to write code detailing what should happen in each step.

It is mainly used in Object-Oriented Programming.

Declarative Style of Programming

The Declarative style of programming prioritizes the desired outcome rather than how to achieve it.

We can focus on specifying the input and output without concerning ourselves with the underlying process.

This style values object immutability, which enhances the program’s stability.

With Java 8, there are plenty of functions in existing packages we can utilize without worrying about the data processing happening in the background.

Functional Programming adopts the ideas of Declarative Programming.

Imperative vs Declarative programming examples

We will write a couple of programs in both Imperative and Declarative ways, so you can see the difference in the code.

Program 1: Imperative Style

Iterate over the elements of an array, sum all even numbers, and return the result as a long.

class Test {

  public static void main(String[] args) {

    int[] array = {7, 8, 12, 41, 13, 98, 12, 18, 15, 72, 65, 90, 39, 40, 81, 10};

    long sum = 0;

    for (int i = 0; i < array.length; i++) {
      if (array[i] % 2 == 0) { // the way to find out if number is even
        sum += array[i];
      }
    }

    System.out.println("The sum of all even numbers is: " + sum);
  }
}
Output: The sum of all even numbers is: 360

Declarative Style

class Test {

  public static void main(String[] args) {

    int[] array = {7, 8, 12, 41, 13, 98, 12, 18, 15, 72, 65, 90, 39, 40, 81, 10};

    long sum = IntStream.of(array)
           .filter(num -> num % 2 == 0)
           .mapToLong(i -> i)
           .sum();

      System.out.println("The sum of all even numbers is: " + sum);
  }
}
Output: The sum of all even numbers is: 360

Program 2: Imperative Style

Write a program that will take an array of strings, go through all the elements, select only those that are longer than 5 characters, sort and return them as a new list.

class Test {

  public static void main(String[] args) {

    String[] names = {"Josh", "Melissa", "James", "Robert", "Jim", "Alexander", "Tom"};

    List<String> resultList = new ArrayList<>();

    for (String element : names) {
      if (element.length() > 5) {
        resultList.add(element);
      }
    }

    // now sort the list
    for (int i = 0; i < resultList.size(); i++) {
      for (int j = resultList.size() - 1; j > i; j--) {
        if (resultList.get(i).compareTo(resultList.get(j)) > 0) {
          String temp = resultList.get(i);
            resultList.set(i, resultList.get(j));
            resultList.set(j, temp);
        }
      }
    }

    // print the elements of a list
    for (String name : resultList) {
      System.out.println(name);
    }
  }
}
Output: Alexander Melissa Robert

Declarative Style

class Test {

  public static void main(String[] args) {

    String[] names = {"Josh", "Melissa", "James", "Robert", "Jim", "Alexander", "Tom"};

    List<String> resultList = Stream.of(names)
             .filter(name -> name.length() > 5)
             .sorted()
             .collect(Collectors.toList());

    resultList.forEach(name -> System.out.println(name));
  }
}
Output: Alexander Melissa Robert
 
See how much more readable the code is and how much easier it is to understand the code written in Declarative style.

In most cases, we will not have to write the logic, but we can use many already-defined functions without being interested in what is happening behind the scenes.
 
In these examples, we used Streams APIs and Lambda expressions. We will cover them in detail in later tutorials.
 
Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *