What is Imperative Programming? With Examples
Imperative programming is a programming paradigm that describes how a program operates and the steps it takes to produce a desired outcome. Simply put, it uses statements that change the program state.
Table of Contents
Introduction
Imperative programming is a software paradigm that uses statements that change the program state.
Java is an object-oriented programming language supporting imperative and functional programming styles.
Imperative programming is a programming paradigm that describes how a program operates and the steps it takes to produce a desired outcome. Simply put, it uses statements that change the program state.
In Java, imperative programming is achieved through loops, if-else statements, and variable assignments. These statements are used to specify the steps that the program should take to produce the desired result.
What is imperative programming?
- It focuses on how to do things.
- In imperative, we treat values as buckets. So the value can be modified in the application at any time.
- Embraces object mutability.
- 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. Think of loops where we iterate through each value, and before processing each item, we update the garbage variable we initialized in the loop.
- Step-by-step instructions on how to achieve an objective.
Examples with detailed explanations
To understand imperative programming, let us write some code with explanations.
- Factorial of a number.
- Remove duplicates.
- Find the largest element in the array of numbers.
- List of objects.
For example, a Java program that calculates the factorial of a given number would use a loop to iterate over the numbers and perform the necessary multiplications.
Overall, Java's support for imperative programming allows for a wide range of control structures and low-level manipulation of program state, making it a versatile language for many types of applications.
Factorial of a number
Here's an example of imperative programming in Java that calculates the factorial of a given number:
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int result = 1;
for (int i = 1; i <= num; i++) {
result *= i;
}
System.out.println("The factorial of " + num + " is " + result);
}
}
Explanation:
- The program uses a for loop to iterate over the numbers from
1
to the input number. - The variable
result
is initialized to1
and is updated on each iteration by multiplying it by the current value ofi
. - The final result, which is the factorial of the input number, is printed to the console.
Remove duplicates
A simple example of removing duplicates with an imperative approach
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class UniqueElements {
public static void main(String[] args) {
List<Integer> integerList =
Arrays.asList(1, 1, 2, 2, 3, 4, 5, 6, 7, 7, 8);
List<Integer> uniqueList = new ArrayList<>();
// "integer" variable is changed/updated for each iteration.
for (Integer integer : integerList) {
if (!uniqueList.contains(integer)) {
uniqueList.add(integer);
}
}
System.out.println("Unique list : " + uniqueList);
}
}
Explanation:
- We have a list of
integer
values stored in aList<>
. - A simple for-loop to iterate elements
!uniqueList.contains(integer)
ignores an element if it's already in the list.- else, add an element to the list.
Do you notice anything? we are mutating/changing variable integer
holding an element and updating the state from one to another.
Finding the largest element in an array of numbers.
import java.util.Scanner;
public class LargestElement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements in the array: ");
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
System.out.print("Enter element " + (i + 1) + ": ");
arr[i] = sc.nextInt();
}
int max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
System.out.println("The largest element in the array is: " + max);
}
}
Explanation:
- The program uses a
for-loop
to readn
elements into an array. - Another
for-loop
is then used to iterate over the elements of the array and determine the largest element. - The variable
max
is initialized to the array's first element and updated on each iteration if a larger element is found. - The final result, the largest element in the array, is printed to the console.
List of Objects
This is yet another simple example containing:
Book
record.- We inflate it with hard-coded data using a
BookRepository
class to avoid connecting to a real database. - Another
main
class to execute the program.
public record Book(String bookTitle, String author, Integer year, Integer copiesSold, Double rating, Double costInEuros) {
public Double getCostInEuros() {
return costInEuros;
}
}
Book
classimport java.util.Arrays;
import java.util.List;
public class BookRepository {
public static List<Book> getAllBooks() {
return 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));
}
}
BookRepository
classimport java.util.ArrayList;
import java.util.List;
public class ImperativeProgramming {
public static void main(String[] args) {
List<Book> books = BookRepository.getAllBooks();
List<Book> imperativeWay = new ArrayList<>();
for (Book book : books) {
if (book.getCostInEuros() >= 5) {
imperativeWay.add(book);
}
}
imperativeWay.forEach(System.out::println);
}
}
Explanation:
- We have a list of
Book
objects stored inList
. - A simple for-loop to iterate
Book
objects. - We have an
if
condition that filters the successful objects and stores them in anotherList
. - Inside
for-loop
, we are constantly changing thebook
variable data and further doingif
checks to filter the data and them into another list.
The same problem as in the previous example, we are mutating/changing variable book
that's holding a Book
object and updating the state from one object to another.
Conclusion:
Imperative programming is a programming paradigm that emphasizes statements that change a program's state and is based on sequences of commands. Java is a versatile language that supports imperative programming and allows for a wide range of control structures and low-level manipulation of program states, making it a powerful tool for many applications.
This concludes the imperative programming, but you will learn more examples in the next lessons.
👨🏻💻 Gopi Gorantala Newsletter
Join the newsletter to receive the latest updates in your inbox.