Open In App

Java – Lambda Expression Variable Capturing with Examples

Last Updated : 24 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Variable defined by the enclosing scope of a lambda expression are accessible within the lambda expression. For example,  a lambda expression can use an instance or static variable defined by its enclosing class. A lambda expression also has access to  (both explicitly and implicitly), which refers to the invoking instance of the lambda expression’s enclosing class. Thus, a lambda expression can obtain or set the value of an intrinsic or static variable and call a method defined by its enclosing class. Lambda expression in java Using a local variable is as stated.

However, when a lambda expression uses a local variable from its enclosing scope, a special situation is created that is referred to as a variable capture. In this case, a lambda expression may only use local variables that are effectively final. An effective final variable is one whose value does not change after it is first assigned. There is no need to explicitly declare such a variable as final, although doing so would not be an error.

It is important to understand that a local variable of the enclosing scope cannot be modified by the lambda expression. Doing so would remove its effective final status, thus rendering it illegal for capture.

There are certain key points to be remembered, which are as follows: 

  • Any local variable, formal parameter, or exception parameter used but not declared in a lambda expression must either be declared final or be effectively final , or a compile-time error occurs where the use is attempted.
  • Any local variable used but not declared in a lambda body must be definitely assigned before the lambda body, or a compile-time error occurs.
  • Similar rules on variable use apply in the body of an inner class . The restriction to effectively final variables prohibits access to dynamically-changing local variables, whose capture would likely introduce concurrency problems. Compared to the final restriction, it reduces the clerical burden on programmers.
  • The restriction to effectively final variables includes standard loop variables, but not enhanced-for loop variables, which are treated as distinct for each iteration of the loop.

The following program illustrates the difference between effectively final and mutable local variables:

Example 1: Effectively Final vs. Mutable Local Variables

Java
// Java Program Illustrating Difference between
// Effectively final and Mutable Local Variables

// Importing reqiored classes
import java.io.*;
// An example of capturing a local variable from the
// enclosing scope

// Inrterface
interface MyFunction {

    // Method inside the interface
    int func(int n);
}

// Main class
class GFG {

    // Main driver method
    public static void main(String[] args)
    {

        // Custom local variable that can be captured
        int number = 10;

        MyFunction myLambda = (n) ->
        {

            // This use of number is OK It does not modify
            // num
            int value = number + n;

            // However, the following is illegal because it
            // attempts to modify the value of number

            // number++;
            return value;
        };

        //Using the Lambda expression 
         System.out.println(myLambda.func(20));
        System.out.println("GFG!");
    }
}

Output
30
GFG!

Explanation of the Program: 

As the comments indicate, number is effectively final and can, therefore, be used inside myLambda. However, if number were to be modified, either inside the lambda or outside of it, number would lose its effective final status. This would cause an error, and the program would not compile. 

Example 2: Using Instance Variables in Lambda Expressions

Java
// Java Program Illustrating Lambda Expression with Instance Variables 

import java.io.*; 

// Interface 
interface MyInterface { 
    void myFunction(); 
} 

// Main class 
class GFG { 
    // Custom initialization
    int data = 170; 

    // Main driver method 
    public static void main(String[] args) { 
        // Creating object of this class 
        GFG gfg = new GFG(); 

        // Creating object of interface 
        MyInterface intFace = () -> { 
            System.out.println("Data: " + gfg.data); 
            gfg.data += 500; 
            System.out.println("Data after modification: " + gfg.data); 
        }; 

        // Using the lambda expression
        intFace.myFunction(); 

        // Modifying the instance variable
        gfg.data += 200; 
        System.out.println("Final Data: " + gfg.data); 
    } 
}

Output
Data: 170
Data after modification: 670
Final Data: 870

Explanation of the Program:

In this example, the lambda expression modifies an instance variable data of the enclosing class GFG. Unlike local variables, instance variables are not subject to the effectively final restriction, so they can be modified both inside and outside the lambda expression.

Note: It is important to emphasize that a lambda expression can use and modify an instance variable from its invoking class. It just can’t use a local variable of its enclosing scope unless that variable is effectively final.



Previous Article
Next Article

Similar Reads

Java Lambda Expression with Collections
In this article, Lambda Expression with Collections is discussed with examples of sorting different collections like ArrayList, TreeSet, TreeMap, etc. Sorting Collections with Comparator (or without Lambda): We can use Comparator interface to sort, It only contains one abstract method: - compare(). An interface that only contains only a single abst
3 min read
Check if a String Contains Only Alphabets in Java Using Lambda Expression
Lambda expressions basically express instances of functional interfaces (An interface with a single abstract method is called functional interface. An example is java.lang.Runnable). lambda expressions implement the only abstract function and therefore implement functional interfaces. Given a String, we just need to iterate over characters again th
3 min read
Serialization of Lambda Expression in Java
Here we will be discussing serialization in java and the problems related to the lambda function without the serialization alongside discussing some ways due to which we require serialization alongside proper implementation as in clean java programs with complete serialization and deserialization process using the function interface. Serialization
5 min read
Lambda Expression in Java
Lambda expressions in Java, introduced in Java SE 8, represent instances of functional interfaces (interfaces with a single abstract method). They provide a concise way to express instances of single-method interfaces using a block of code. Functionalities of Lambda Expression in JavaLambda Expressions implement the only abstract function and there
5 min read
Packet Capturing using JnetPcap in Java
What is JnetPcap? JnetPcap is an open-source Java library. It is java wrapper for all libpcap library native calls. It can be used to capture both live as well as offline data. Decoding packets is a special feature of Jnetpcap. For processing packets, you need pcap files which can be generated by using Wireshark. JNETPCAP Installation Steps: For Wi
5 min read
Difference between Anonymous Inner Class and Lambda Expression
Anonymous Inner Class:It is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain "extras" such as overloading methods of a class or interface, without having to actually subclass a class.Anonymous inner classes are useful in writing impl
3 min read
Java 11 Lambda Features with Examples
In essence, lambda expressions express examples of functional interfaces (a functional interface is an interface with a single abstract method). Java.lang. Runnable is an excellent example. Lambda expressions, which also implement functional interfaces, implement the lone abstract function. In Java 11, lambda expressions were added, and they offer
3 min read
Block Lambda Expressions in Java
Lambda expression is an unnamed method that is not executed on its own. These expressions cause anonymous class. These lambda expressions are called closures. Lambda's body consists of a block of code. If it has only a single expression they are called "Expression Bodies". Lambdas which contain expression bodies are known as "Expression Lambdas". B
4 min read
How to Create Thread using Lambda Expressions in Java?
Lambda Expressions are introduced in Java SE8. These expressions are developed for Functional Interfaces. A functional interface is an interface with only one abstract method. To know more about Lambda Expressions click here. Syntax: (argument1, argument2, .. argument n) -> { // statements }; Here we make use of the Runnable Interface. As it is
3 min read
Java - Lambda Expressions Parameters
Lambda Expressions are anonymous functions. These functions do not need a name or a class to be used. Lambda expressions are added in Java 8. Lambda expressions express instances of functional interfaces An interface with a single abstract method is called a functional interface. One example is java.lang.Runnable. Lambda expressions implement only
5 min read
Effectively Final Variable in Java with Examples
A final variable is a variable that is declared with a keyword known as 'final'. Example: final int number; number = 77; The Effectively Final variable is a local variable that follows the following properties are listed below as follows: Not defined as finalAssigned to ONLY once. Any local variable or parameter that's assigned a worth just one occ
4 min read
How to Make Java Regular Expression Case Insensitive in Java?
In this article, we will learn how to make Java Regular Expression case-insensitive in Java. Java Regular Expression is used to find, match, and extract data from character sequences. Java Regular Expressions are case-sensitive by default. But with the help of Regular Expression, we can make the Java Regular Expression case-insensitive. There are t
2 min read
Lambda Expressions in Android with Example
Lambda expressions are a feature of Java 8 and later, which can be used in Android development to simplify code and improve readability. They are anonymous functions that can be passed around as values and can be used to create functional interfaces, which are interfaces that have a single abstract method. In Android, lambda expressions can be used
4 min read
How to Use Regular Expression as a Substitute of endsWith() Method in Java?
So primarily discuss what is endsWith() method is, so it is a method of String class that checks whether the string ends with a specified suffix. This method returns a boolean value true or false. Syntax: public boolean endsWith(String suff) Parameter: specified suffix part Return: Boolean value, here in java we only have true and false. Methods: W
3 min read
Build a Calculate Expression Game in Java
Java is a class-based, object-oriented programming language and is designed to have as few implementation dependencies as possible. A general-purpose programming language made for developers to write once run anywhere that is compiled Java code can run on all platforms that support Java. Java applications are compiled to byte code that can run on a
14 min read
Java Numeric Promotion in Conditional Expression
With recurrence use of if-else condition in programming which is tend to occur no matter how much we optimize our code. So taking this factor into consideration, conditional operator was introduced making our job of writing code easier as it do have a specific syntax in accordance to which it does check the condition passed to it. The conditional o
2 min read
Java Program to Evaluate an Expression using Stacks
Evaluating arithmetic expressions is a fundamental problem in computer science. This problem can be efficiently solved using the stack data structures. Stack can operate on the last in First Out(LIFO) principle which is particularly useful for parsing expressions and ensuring the proper operator precedence and associativity. The main concept behind
5 min read
Overloading Variable Arity Method in Java
Here we will be discussing the varargs / variable arity method and how we can overload this type of method. So let us first understand what a variable arity method is and its syntax. A variable arity method also called as varargs method, can take a number of variables of the specified type. Note: Until version 1.4 there is no varargs method. It was
5 min read
Initialization of local variable in a conditional block in Java
Java comprises 5 conditional blocks namely - if, switch, while, for and try. In all these blocks, if the specified condition is true, the code inside the block is executed and vice-versa. Also, Java compiler doesn't let you leave a local variable uninitialized. While initializing local variable inside a conditional block, one must bear the followin
3 min read
What is the difference between field, variable, attribute, and property in Java
Variable A variable is the name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. Each variable has a type, such as int, double or Object, and a scope. Class variable may be instance variable, local variable or constant. Also, you should know that some p
2 min read
Why non-static variable cannot be referenced from a static method in Java
Java is one of the most popular and widely used programming language and platform. Java is Object Oriented. However, it is not considered as a pure object-oriented as it provides support for primitive data types (like int, char, etc). In java, methods can be declared as either static or non-static. In this article, let's discuss why non-static vari
4 min read
Rules For Variable Declaration in Java
Variable in Java is a data container that saves the data values during Java program execution. Every variable is assigned a data type that designates the type and quantity of value it can hold. Variable is a memory location name of the data. A variable is a name given to a memory location. For More On Variables please check Variables in Java. Synta
2 min read
Creating Multiple Pools of Objects of Variable Size in Java
Object pool pattern is a software creational design pattern that is used in situations where the cost of initializing a class instance is very high. Basically, an Object pool is a container that contains some amount of objects. So, when an object is taken from the pool, it is not available in the pool until it is put back. Objects in the pool have
10 min read
Array Variable Assignment in Java
An array is a collection of similar types of data in a contiguous location in memory. After Declaring an array we create and assign it a value or variable. During the assignment variable of the array things, we have to remember and have to check the below condition. 1. Element Level Promotion Element-level promotions are not applicable at the array
3 min read
Variable Arguments (Varargs) in Java
Variable Arguments (Varargs) in Java is a method that takes a variable number of arguments. Variable Arguments in Java simplifies the creation of methods that need to take a variable number of arguments. Need of Java VarargsUntil JDK 4, we cant declare a method with variable no. of arguments. If there is any change in the number of arguments, we ha
4 min read
Instance Variable Hiding in Java
One should have a strong understanding of this keyword in inheritance in Java to be familiar with the concept. Instance variable hiding refers to a state when instance variables of the same name are present in superclass and subclass. Now if we try to access using subclass object then instance variable of subclass hides instance variable of supercl
2 min read
Java Program to Swap two Strings Without Using any Third Variable
Given two string variables, a and b, your task is to write a Java Program to swap these variables without using any temporary or third variable. Use of library methods is allowed. Examples: Input: a = "Hello" b = "World" Output: Strings before swap: a = Hello and b = World Strings after swap: a = World and b = Hello Method 1 : In order to swap two
4 min read
Using predefined class name as Class or Variable name in Java
In Java, you can use any valid identifier as a class or variable name. However, it is not recommended to use a predefined class name as a class or variable name in Java. The reason is that when you use a predefined class name as a class or variable name, you can potentially create confusion and make your code harder to read and understand. It may a
5 min read
Using _ (underscore) as Variable Name in Java
As we do know variables in java or rather in any language is introduced to write a code where it is suggested to give meaningful names to the variables as per their usage in code and especially in object-oriented languages are supposed to be used locally wherever it is possible instead of just using them globally. It is a very essential property of
3 min read
Instance variable as final in Java
Instance variable: As we all know that when the value of variable is varied from object to object then that type of variable is known as instance variable. The instance variable is declared inside a class but not within any method, constructor, block etc. If we don’t initialize an instance variable, then JVM automatically provide default value acco
3 min read
Article Tags :
Practice Tags :