Implement Lambda Expression in JShell in Java 9



In this article, we will learn to implement a lambda expression in JShell in Java 9. We will learn the syntax, explain the working of lambda expressions, and how they work with functional interfaces, and give examples with the JShell environment.

JShell

JShell is Java's first REPL and command-line tool that provides interactive use of Java programming language elements. We can test the functionality in isolation of a class by using this tool. JShell creates a simple and easy programming environment in the command-line that takes input from the user, reads it, and prints the result.

What is a Lambda Expression?

Lambda expressions were introduced in Java 8. Lambda expressions are similar to methods in Java, that they do not need a name, and they can be used inside a method directly.


Lambda Expression in JShell

A lambda expression in JShell is the same as a lambda expression in Java programming that is created without belonging to any class. We can creatre a lambda expression in JShell by following the syntax of the basic lambda expression that is definded above.

Syntax

Below is the syntax for a lambda expression usage:

parameters(arguments) -> expression

Here we are going to define a functional interface as "Consumer". Consumer is a built-in Java interface that takes a single input. Here, we are taking a string as a single input.

The variable name we're assigning to the lambda is "s". System.out.println(s) is the expression(body of the lambda) that takes the input string "s" and prints its value.

The value that is generated is $Lambda$14/1268066861@3159c4b8 :

  • $Lambda$14: It shows that it is the 14th lambda created in the current session.
  • 1268066861: The number is a unique identifier.
  • @3159c4b8: It represents the memory address.

Example to implement a lambda expression in JShell

In the below example, we can implement a lambda expression in JShell.

C:\Users\User>jshell
| Welcome to JShell -- Version 9.0.4
| For an introduction type: /help intro

jshell> Consumer<String> s = (String s) -> System.out.println(s)
s ==> $Lambda$14/1268066861@3159c4b8

If we can't remember the method of the Consumer interface, then type the name of a variable created, followed by a dot, and press tab. It populates a list of methods that can be called on the Consumer interface.

jshell> s.
accept() andThen() equals() getClass() hashCode()
notify() notifyAll() toString() wait()

jshell> s.accept("Welcome to Tutorialspoint")
Welcome to Tutorialspoint
Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-06-09T19:29:50+05:30

333 Views

Kickstart Your Career

Get certified by completing the course

Get Started