Pure & Impure Methods in Java

In Java, methods can be classified as pure methods and impure methods based on whether they change data outside the method or produce side effects.

Pure Methods

A pure method does not modify any object or variable outside the method. It gives the same output for the same input every time. It has no side effects (such as printing, changing variables, writing files, etc.).

Example

class Demo{
    int square(int n){
        return n * n;
    }
    public static void main(String args[]){
        Demo obj = new Demo();
        int result = obj.square(5);
        System.out.println("Square = " + result);
    }
}

The above method is pure because it only calculates and returns a value. It does not change any external variable or object.

Impure Methods

An impure method changes object data or external variables, or produces side effects printing output, taking input, updating files, etc.

Example

class Demo{
    int count = 0;
    void increment(){
        count++;
    }
    public static void main(String args[]){
        Demo obj = new Demo();
        obj.increment();
        obj.increment();
        System.out.println("Count = " + obj.count);
    }
}

The above method is impure because it changes the value of the instance variable count. The result depends on the object's previous state.

Comments