Closure in Java with Example

Java is an object-oriented programming language, and everything in Java revolves around an object. Since Java 8, the priority has shifted to functional aspects of programming. Obtaining the desired output from a program using only objects was found to be inconvenient. Replacing it with functions would be more efficient in many cases.

Closure in Java comes hand-in-hand with Lambda expression. This article will give glimpses of Java Closure with Lambda expression and its implementation.

Lambda expression:

A method without a name, access specifier, and the return value is a lambda expression. These are known as anonymous methods or closure. There exists a similar concept called an anonymous class. The class has no name here, yet an object can be created. Similarly, a lambda expression is a method that has no name but performs a specific task. It can also contain parameters. In other words, it represents functional interfaces like Runnable, Predicate, Function, Callable, etc.

Here is an example that will explain this concept more clearly:
public void print()
{
System.out.println(“DataFlair”);
}

This is a snippet of a method that would print the given details. Now, let us change this method into a lambda expression. And to do so, we should remove the access specifier 'public', the return type 'void', and the method's name, 'print'. 

It will be written as:
() -> {
System.out.println(“DataFlair”);
}

The empty parentheses denote that the method does not contain any parameters. Finally, the arrow symbol (->) acts as a separator between the method header and the body.

The same lambda expression can also be written in a single line as given below:

() -> { System.out.println(“DataFlair”); }

In case we need to pass values and perform certain operations, the lambda expression would be framed in the given way:

(int m, int n) -> {System.out.println(“Sum = ” (m+n));}

Categories of lambda expression:

Lambda expressions are categorised into two types:

1. Open Expression: In this type, a few symbols are not bound. It denotes that some symbols present in them are free and contain external information.

2. Closed Expression: In this type, the expressions are self-contained. They are not bound to the surrounding context for evaluation. These expressions are also known as combinators.

Java 8 Lambda Limitations:

The Lambda expression’s intromission scope entirely has access to the final variables. For instance, consider the following example:

void fn()

No compilation takes place as the incrementation of myVar is final.

JavaScript and its Functions:

In JavaScript, the Functions and Lambda expressions use closure:

A closure is a special type of object that combines a function and the environment in which the function was created. It consists of local variables. Here is an example to show the function’s working in JavaScript:

function examplefn() { 
var myVar = 50;
var lambdaFun = () => myVar;
myVar++;
console.log(lambdaFun()); // it prints 51
}

Closure in Java:

A closure is a method or a function that denotes the free variables in the lexical context. It is an inline-function valued expression, meaning they are class functions with bounded variables. As we already know, a method consists of a block of statements that execute when the method is called. It also returns a value as an output.

A free variable is an identifier that does not contain a definition given by the closure. Therefore, a closure can access variables not defined in the list of parameters. The closure can also be parsed like a parameter.

Simply put, a lambda expression becomes a closure when it can access variables that do not come under its scope. This makes the lambda access the variables outside its scope. We should also remember that inner classes are not closure in Java.

Need of Java Closure

Closure helps in providing data privacy. Another feature that it provides is currying. It means it breaks a function with multiple parameters as several functions into a single argument.

Goal of closure in Java

As we just saw, it is used to protect data. One of the fundamental reasons to use closure is it shorts the function literals avoiding anonymous instances and interoperating with the current APIs. It also performs functional and aggregate operations.

Declaration:

We can declare a closure in the same way as we did for the lambda expression.

Syntax:

(argument_list) -> {function_body}

Code to implement Java Closure:

Firstly, we will create an interface named ClosureInterface.

ClosureInterface.java<br />
package com.dataflair;<br />
@FunctionalInterface<br />
public interface ClosureInterface
{
void performOperation(int n);
}

ClosureCode.java

package com.dataflair; 
public class ClosureCode  
{  
public static void main(String args[])  
{  
int x=50;  
int y=30;  
doSum(x, new ClosureInterface()  
{  
//overrides the performOperation() method      
@Override  
public void performOperation(int n)  
{      
System.out.println("Sum is: "+(n+y));  
}  
});  
}  
private static void doSum(int i, ClosureInterface ci)  
{  
ci.performOperation(i);  
}  
}  

Output:
Sum is: 80

Code to implement closure using a lambda expression:

package com.dataflair;<br />
public class ClosureCode
{  
public static void main(String args[])  
{  
int x=50;  
int y=30;  
doSum(x, n->System.out.println(n+y));  
}  
private static void doSum(int i, ClosureInterface ci)  
{  
ci.performOperation(i);  
}  
}  

Output:

80

Conclusion:

I hope you now have a clear idea about the closure in Java by now. Though we do not use it often, it is indispensable in Java programming to provide security. You can try the given example programs to check out their implementation.

Leave a Reply

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