Closures in Java with Examples

26 Jul, 2021
A method is a collection of statements that perform some specific task and return the result to the caller. A method can perform some specific task without returning anything. Methods allow us to reuse the code without retyping the code. In Java, every method must be part of some class which is different from languages like C, C++, and Python. In this article, we will understand one type of functions named closures. Before getting into the closures, lets first understand what a lambda expression is. A lambda expression basically expresses instances of the functional interfaces(An interface with a single abstract method is called a functional interface). An example is java.lang.Runnable. Lambda expressions implement the only abstract function and therefore implement functional interfaces. Lambda expressions are added in Java 8 and provide below functionalities:  
Enable to treat functionality as a method argument, or code as data.A function that can be created without belonging to any class.A lambda expression can be passed around as if it was an object and executed on demand.
Enable to treat functionality as a method argument, or code as data.
A function that can be created without belonging to any class.
A lambda expression can be passed around as if it was an object and executed on demand.
The main limitation of the lambda expression is that the scope for the lambda expressions will only be final. That is, we cant change the value of the variables in the lambda expressions. Suppose we define a lambda expression in which we increment the value of a variable, it simply throws an error. In order to solve this error, the closures have been defined. Closures are the inline-function valued expressions which means that they are the class functions with bounded variables. Closures can be passed to another function as a parameter. A closure gives us access to the outer function from an inner function. But as of Java 1.6, Java does not rely on closures or java does not have closures. Also, anonymous inner classes are not closures in Java. Using closures helps in data privacy and currying (currying means breaking a function with many parameters as a number of functions in a single argument). Though the concept of closure is much more well defined in Javascript, the closures can still be implemented using lambda expressions. The syntax to implement a closure is:  
(argument_list) -> {func_body}
Now, let’s understand how to implement the closures with examples: 
 
Example 1: In this example, we will first implement a lambda expression without a parameter or an argument.  
Java
// Java program to demonstrate// how a closure is implemented// using lambda expressions import java.io.*; // Defining an interface whose// implementation is given in// the lambda expression.// This uses the concept of// closuresinterface SalutationInterface {    public String salHello();} class GFG {     // Driver code    public static void main(String[] args)    {        // Lambda Expression        SalutationInterface obj = () ->        {            return "Hello, GFGians!";        };         // Calling the above interface        System.out.println(obj.salHello());    }}
Hello, GFGians!
 
Example 2: In this example, we will understand how to implement the lambda expression which takes multiple parameters.  
Java
// Java program to demonstrate// how a closure is implemented// using lambda expressionsimport java.io.*; // Defining an interface whose// implementation is given in// the lambda expression.// This uses the concept of// closuresinterface concatStrings {    public String concat(String a,                         String b);} class GFG {     // Driver code    public static void main(String[] args)    {        // Lambda Expression        concatStrings s = (s1, s2)            -> s1 + s2;         System.out.println(            s.concat("Hello, ",                     "GFGians!"));    }}
Hello, GFGians!
 
Example 3: In this example, we are going to use a custom functional interface to display the month from the number provided. 
Java
// Java program to demonstrate// how a closure is implemented// using lambda expressions import java.io.*; // Defining an interface whose// implementation is given in// the lambda expression.// This uses the concept of// closuresinterface NumToMonth {    public String convertToMonth(int x);} class GFG {     // Driver code    public static void main(String[] args)    {         // Lambda Expression         NumToMonth obj = new NumToMonth() {            String[] months = { "Jan", "Feb", "Mar",                                "Apr", "May", "Jun",                                "Jul", "Aug", "Sep",                                "Oct", "Nov", "Dec" };             public String convertToMonth(int n)            {                return (n > 0 && n <= months.length)                    ? months[n - 1]                    : null;            };        };        System.out.println(obj.convertToMonth(8));    }}
Aug
 
 
rolf6
Functions
Java 8
java-lambda
Java
Java
Functions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java