Java REPL – JShell Complete Guide

Introduction

Java REPL or JShell is a new interactive java shell tool. JShell is basically a REPL tool which runs from the command line. REPL stands for Read Evaluate Print Loop.

First Java REPL tool – Jshell was introduced in java version 9.

In this article, we will learn Java Jshell and REPL basics and we will also learn some commands.

Let’s get started –

What is REPL ?

JShell is a Java REPL tool so before learning Jshell, we must know what is REPL. REPL (Read-Evaluate-Print-Loop) is an interactive and well known shell tool.

It is used in various programming languages. This tool is more common in languages like Node , Python etc which are scripting languages.

REPL tool allows the programmers to execute the code/commands from the shell / command prompt and these commands will get executed immediately and result is displayed.

These type of tool helps in trying the new ideas or logic quickly without writing a lot of code. We do not need to write extra code to test our idea or logic, we can run the command and test the logic immediately.

As the name suggests, This is all about an immediate feedback tool and it reads, evaluates, prints and loops quickly.

Finally one Java REPL tool with the name of JShell is released in Java 9.

Why REPL ?

REPL is popular tool in many programming languages. REPL is an important tool but it was released very late in Java. Let’s understand why it was needed?

As we all know about Scala which is a programming language to develop small and large applications. Scala is a popular language because of its several features and advantages.

It has the multi-paradigm support i.e. Object-oriented and Functional programming support . It also has support of REPL.

Oracle corporation is trying to have all the good features and advantages of Scala into Java. In Java 8, various functional programming approaches were already introduced like the Lambda expressions etc.

REPL (Read Evaluate Print Loop) is one of the best feature of Scala. It is a command line interface to execute the Scala programs / logics. Developers can easily use the REPL in Scala and learn the basic fundamental of Scala language.

Due to its features , Java 9 finally brings the shell functionality in the form of JShell.

What is JShell ?

JShell is Java’s first official REPL application. It was released in Java 9. It Stands for Java Shell. It is a tool which helps in executing and evaluating simple java programs and small logics such as statements, simple programs, loops , expressions etc.

We do not need to wrap these logics or code into classes or methods, they can be directly evaluated and will return result. It helps in testing the logic very quickly without writing huge unnecessary code.

Java REPL provides simple programming environment in the command line prompt. It reads the input, evaluates it, prints the output and repeat same cycle.

As it does not need any additional editors , It is beneficial for the beginners to learn the new features and to test the same.

Advantages of JShell

Java REPL has hugely reduced the efforts that are required to run even a simple Java program to test the business logic.

If it is not used for creating and testing the simple logics, below mentioned steps are required for testing the logic. Even if you want to just test one simple loop.

  • Install the editor to write a Program.
  • Create the class.
  • Compile the program.
  • Solve the Compilation errors, If any.
  • Run the program.
  • Solve the Runtime errors, If any.
  • Repeat the process.

With JShell, These steps are not required. We can very easily evaluate statements, classes and methods and even can write Hello World program without creating class.

Launching JShell

It is super easy to launch as it is official component of Java 9 JDK. Please ensure your Java version is 9 or higher to test REPL.

Once Java 9 is installed, JShell can be started by executing jshell command :

$ jshell
|  Welcome to JShell -- Version 9
|  For an introduction type: /help intro
jshell> 

Hello World! JShell

Let’s write our first Hello World! example using it in Java :

jshell> System.out.println("Hello World!")
Hello World!

That’s all is required. We have not created the class, not created the main method. We have only written the print statement and just after clicking Enter , Output is presented.

One thing is to be remember about it is that we do not require to add Semicolons . It is optional for single statements. However, Semicolons are required with multi line statements and methods.

Further Jshell Configuration

We can also control behavior of it by providing additional commands. We have several additional options which can be configured in this.

We can configure it to load additional external classes whether in the form of JAR files or new Java Module format.

We can specify the JAR file to load using Java classpath either by setting the CLASSPATH environment variable or using the command line option -class-path.

See below :

$ jshell --class-path junit-4.12.jar
|  Welcome to JShell -- Version 9
|  For an introduction type: /help intro
==> import org.junit.Test
==>

We can specify Java modules using the command :

  • –add-modules
  • –module-path
$ jshell --add-modules jdk.incubator.httpclient
|  Welcome to JShell -- Version 9
|  For an introduction type: /help intro
==> import jdk.incubator.http.*;
==>

We have more options like adjusting the feedback mode, it is the level of output for any executing commands. We can use the -feedback option for this with the parameter – silent, verose, concise or normal.

See Below :

$ jshell --feedback verbose
|  Welcome to JShell -- Version 9
|  For an introduction type: /help intro
==> 1+1
$1 ==> 2
|  created scratch variable $1 : int
==>

We can also load any script on startup , we can provide additional predefined options as well. It can be specified using the command –startup flag. We can pass file name or below options with this command :

  1. DEFAULT : It loads the default behavior. It works as same as nothing is specified.
  2. JAVASE : It imports all the Java SE packages by default.
  3. PRINTING : It is used to define the functions print, println and printf for use.
$ jshell --startup PRINTING
|  Welcome to J Shell -- Version 9
|  For an introduction type: /help intro
==> printf("%d\n", 5)
5
==>

Variables and Expressions in JShell

We can evaluate any valid Java expression using this. We can evaluate any expressions like string concatenation, method invoking, arithmetic operations etc.

jshell> 8+2
$1 ==> 10
jshell> 11*7
$2 ==> 77

We can see that it automatically creates variable to store the results obtained after execution. These variable names are prefixed with $. See below example, where we are performing expression by providing variable names :

jshell> $1 + $2
$3 ==> 87

All above variables are automatically created by it. If we want, we can create own variables.

Refer below example :

jshell> int distance = 30
distance ==> 30
jshell> int time = 3
time ==> 3
jshell> int speed = distance / time
speed ==> 10

We can also manipulate String using JShell , See Below examples :

jshell> "Tech " + "Blog " + "Station"
$7 ==> "Tech Blog Station"
jshell> String name = "TechBlogStation"
name ==> "TechBlogStation"
jshell> name.toUpperCase()
$9 ==> "TECHBLOGSTATION"
jshell> name.substring(0, 4)
$10 ==> "Tech"

Control Flow Statements (If-Else, While-Loops, For-Loops) in JShell

We can also execute multiple-lines control flow statements using it. Control flow statements like If-else,for-loops etc can be executed in it. It recognizes multiple-lines statements are prompts with symbol “…>” to indicate to enter the next line statement.

Example of If-Else statement :

jshell> int distance = 50
distance ==> 50
jshell> if(distance < 30) {
   ...>     System.out.println("Near!!!!");
   ...> } else {
   ...>     System.out.println("Far!!!!");
   ...> }
Far!!!!

Example of While Loop

jshell> int i = 1
i ==> 1
jshell> while(i < 15) {
   ...>     System.out.print(i + " ");
   ...>     i++;
   ...> }
1 2 3 4 5 6 7 8 9 10 11 12 13 14

Example of For Loop :

jshell> String[] friends= {"Rachel", "Ross", "Phoebe", "Joey", "Chandler", "Monica"}
friends ==> String[6] {"Rachel", "Ross", "Phoebe", "Joey", "Chandler", "Monica"}
jshell> for(String friend : friends) {
   ...>     System.out.println(friend);
   ...> }
Rachel
Ross
Phoebe
Joey
Chandler
Monica

Defining and Invoking Methods in JShell

Similar to Java classes, we can define and invoke methods in JShell . See Below Example :

jshell> int add(int x, int y) {
   ...>     return x + y;
   ...> }
|  created method add(int,int)

Above example creates one method, Now we can call this method but only in this Session only.If you quit the current session, method will be no longer available :

jshell> add(10, 4)
$12 ==> 14

Creating Classes and Objects in JShell

We can create Classes and Objects in JShell as well. Additionally, Creating interfaces , enums etc is also allowed in the Java REPL – JShell :

jshell> class Animal {
   ...>     private String name;
   ...>     Animal(String name) {
   ...>         this.name = name;
   ...>     }
   ...>     String getName() {
   ...>         return name;
   ...>     }
   ...>     void setName(String name) {
   ...>         this.name = name;
   ...>     }
   ...> }
|  created class Animal
jshell> Animal animal = new Animal("Cat")
c ==> Animal@1ce67523
jshell> animal.getName()
$3 ==> Cat

Exploring JShell Commands

JShell does not only supports executing Statements and Expressions but it also provide multiple additional meta commands to explore REPL functionalities.

These commands can be used for listing all the variable in the current session , list the methods and imports available in the current session, See the history, Edit the created method or variable etc.

List of all these type of commands can be seen in JShell by typing /help or /? in the JShell session.

Let’s see some of these command with examples :

/imports : List all available imports in JShell session

By Default, JShell automatically imports some useful Java packages when the JShell session is started. Type the command /imports in JShell window to get the list of all these imports –

jshell> /imports
|    import java.io.*
|    import java.math.*
|    import java.net.*
|    import java.nio.file.*
|    import java.util.*
|    import java.util.concurrent.*
|    import java.util.function.*
|    import java.util.prefs.*
|    import java.util.regex.*
|    import java.util.stream.*

We can always import any additional Java package in session like this –

jshell> import java.time.*

If you have imported any additional package in your session, /imports will also show these imports as well.

/vars : List all the variables defined in the current JShell session

To List all the variables created in the current JShell session, we can use /vars command which will show the list of all the variables along with their values.

jshell> /vars
|    int $1 = 10
|    int $2 = 77
|    int $3 = 87
|    int distance = 30
|    int time = 3
|    int speed = 10
|    String $7 = "Tech Blog Station"
|    String name = "TechBlogStation"
|    String $9 = "TECHBLOGSTATION"
|    String $10 = "Tech"

/methods : List all the methods defined in the current JShell session

/methods command simply shows all the methods defined in the current JShell session :

jshell> /methods
|    int add(int,int)

/types : List all the classes, interfaces and enums defined in the current JShell session

/types command shows the created classes, interfaces etc in the current JShell session :

jshell> /types
|    class Animal

/edit : Edit an already defined method, variable or class

We can use /edit command to edit any already created method or variable. Let’s see below example, where we are editing the current existing add() method :

jshell> /edit add

As we enter the /edit command in the JShell, it opens a new editor where we can edit and save the method. After closing the new opened editor, JShell shows the message that the method is modified :

|  modified method add(int,int)

/set : Set JShell configuration info

We can configure the environment using the /set command.

In the previous section, we used the /edit command to edit the method and JShell opens a new editor to edit the method. JShell opens the default editor in this case. If we want to change the editor for JShell, We can use the below command :

jshell> /set editor vim
|  Editor set to: vim

This will change the default editor to vim.

/save : Save the current workspace to a file

We can always save the current session data , that means whatever you have typed in the current session, in a file using the below command :

jshell> /save JShellOne.txt

/open : Open an already saved workspace

We can open the file as a source input for the current session by using /open command :

jshell> /open JShellOne.txt

Not just we can load the commands from the external files but we can also load a class in the current session from an external file using /open command :

Suppose you have created a class named as Shape in the current working directory. We can use below command to load that class in the current JShell session :

jshell> /open Shape.java

Now, By using the command /types we can check the current JShell session classes :

jshell> /types
|    class Animal
|    class Shape

Conclusion

In this post, we have learned about REPL, JShell basic, JShell Commands with Examples etc.

Newsletter Updates

Enter your name and email address below to subscribe to our newsletter

Leave a Reply