Closures in Java with Examples
Last Updated :
05 Jun, 2023
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 that is different from languages like C, C++, and Python. In this article, we will understand one type of function named closures.
Lambda Expression in Java
Before getting into the closures, let's 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.
Functionalities of Lambda Expressions
Lambda expressions implement only abstract functions and therefore implement functional interfaces. Lambda expressions are added in Java 8 and provide the 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.
The main limitation of the lambda expression is that the scope for the lambda expressions will only be final. That is, we can't 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.
Examples of Lambda Expression
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
// closures
interface SalutationInterface {
public String salHello();
}
// Driver Class
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());
}
}
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 expressions
import java.io.*;
// Defining an interface whose
// implementation is given in
// the lambda expression.
// This uses the concept of
// closures
interface concatStrings {
public String concat(String a, String b);
}
// Driver Class
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!"));
}
}
Closures in Java
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, closures can still be implemented using lambda expressions.
Java Closures Syntax
The syntax to implement a closure is:
(argument_list) -> {func_body}
Examples of the Java Closures
Now, let's understand how to implement the closures with examples:
Example 1: 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
// closures
interface NumToMonth {
public String convertToMonth(int x);
}
// Driver Class
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));
}
}
Example 2:
Java
// Java Pogram to implement
// to calculate the result
// using Closure and lamda methods
@FunctionalInterface
public interface Operation {
void operate(int n);
}
ClosureExample.java package com.javatpoint;
public class GFG {
public static void main(String args[])
{
int a = 12;
int b = 88;
// implementation of closure in lambda expression
temp(a, new Operation() {
// overrides the operate() method
@Override public void operate(int n)
{
// prints the result
System.out.println("Result is: " + (n + b));
}
});
}
private static void temp(int i, Operation op)
{
op.operate(i);
}
}
Output:
Result is: 100
Closure vs Lambda
Both lambda and closure are quite similar to each other the difference can be understood using the difference between a class and an instance of the class. A Class exists only in the source code, and it doesn't exist during the runtime. There are only objects of the class type during the runtime. Similarly, Closures are to lambdas as objects are to classes.
Similar Reads
Calendar Class in Java with examples
Calendar class in Java is an abstract class that provides methods for converting date between a specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It inherits Object class and implements the Comparable, Serializable, Cloneable interfaces. As it is an Abstract class
4 min read
Writer close() method in Java with Examples
The close() method of Writer Class in Java is used to close the writer. Closing a writer deallocates any value in it or any resources associated with it. The Writer instance once closed won't work. Also a Writer instance once closed cannot be closed again. Syntax: public void close() Parameters: Thi
2 min read
Reader close() method in Java with Examples
The close() method of Reader Class in Java is used to close the stream and release the resources that were busy in the stream, if any. This method has following results: If the stream is open, it closes the stream releasing the resources If the stream is already closed, it will have no effect. If an
2 min read
Scanner close() method in Java with Examples
The close() method ofjava.util.Scanner class closes the scanner which has been opened. If the scanner is already closed then on calling this method, it will have no effect. Syntax: public void close() Return Value: The function does not return any value. Below programs illustrate the above function:
1 min read
Constructor Chaining In Java with Examples
Constructor chaining is the process of calling one constructor from another constructor with respect to current object. One of the main use of constructor chaining is to avoid duplicate codes while having multiple constructor (by means of constructor overloading) and make code more readable. Prerequ
5 min read
Open Closed Principle in Java with Examples
In software development, the use of object-oriented design is crucial. It helps to write flexible, scalable, and reusable code. It is recommended that the developers follow SOLID principles when writing a code. One of the five SOLID principles is the open/closed principle. The principle states that
9 min read
Formatter close() method in Java with Examples
The close() method is a built-in method of the java.util.Formatter which closes the formatter. In case it is already closed, it will have no effect. Closing it means that it will release the resources that it is already holding. Syntax: public void close() Parameters: The function accepts no paramet
2 min read
List clear() method in Java with Examples
The clear() method of List interface in Java is used to remove all of the elements from the List container. This method does not deleted the List container, instead it just removes all of the elements from the List. Example:Java// Java Program to Demonstrate // List clear() import java.util.*; class
2 min read
Abstract Method in Java with Examples
In Java, Sometimes we require just method declaration in super-classes. This can be achieved by specifying the Java abstract type modifier. Abstraction can be achieved using abstract class and abstract methods. In this article, we will learn about Java Abstract Method. Java Abstract MethodThe abstra
6 min read
Class forName() method in Java with Examples
The forName() method of java.lang.Class class is used to get the instance of this Class with the specified class name. This class name is specified as the string parameter.Syntax: public static Class<T> forName(String className) throws ClassNotFoundException Parameter: This method accepts the
1 min read