In Java, the concepts of pure and impure functions are
rooted in functional programming principles,
although Java is primarily an object-oriented
language.
Pure Function:
A pure function in Java adheres to two main
characteristics:
• Determinism:
Given the same input arguments, it will always
produce the same output. It does not rely on any
external state or mutable data that can change
over time.
• No Side Effects:
It does not cause any observable changes outside
its local scope. This means it does not modify
global variables, object states, perform I/O
operations (like printing to console or writing to
files), or interact with external systems.
Impure Function:
An impure function, conversely, violates one or both
of the characteristics of a pure function:
• Non-Determinism:
It may produce different outputs for the same
input arguments, often due to reliance on
external, mutable state.
• Side Effects:
It causes observable changes outside its local
scope, such as modifying global variables,
changing object states, or performing I/O
operations.
Program Example:
Java
public class FunctionTypes {
// Global variable (mutable state)
private static int counter = 0;
// Pure Function Example
public static int add(int a, int b) {
return a + b; // Always returns the same sum for the same
inputs
}
// Impure Function Example (modifies global state)
public static int incrementAndGetCounter() {
counter++; // Modifies external state (global variable)
return counter;
}
// Another Impure Function Example (side effect: printing)
public static void printMessage(String message) {
System.out.println(message); // Performs I/O operation (side
effect)
}
public static void main(String[] args) {
// Pure function usage
int sum1 = add(5, 3);
int sum2 = add(5, 3);
System.out.println("Pure function (add): " + sum1 + ", " +
sum2); // Output: 8, 8
// Impure function usage (modifying global state)
System.out.println("Impure function
(incrementAndGetCounter): " + incrementAndGetCounter()); //
Output: 1
System.out.println("Impure function
(incrementAndGetCounter): " + incrementAndGetCounter()); //
Output: 2
// Impure function usage (side effect: printing)
printMessage("Hello from an impure function!");
}
}
In the example:
• The add method is a pure function because it only
takes inputs, returns a value based solely on
those inputs, and has no side effects.
• The incrementAndGetCounter method is an impure
function because it modifies the counter global
variable, which is an external state. Calling it
multiple times with no arguments yields different
results.
• The printMessage method is also an impure function
because it performs an I/O operation by printing
to the console, which is a side effect.