Core Java

Java 9 Repl Tutorial

In this example, I would like to show you how to get started with Java 9 REPL (The Java Shell: Read-Eval-Print Loop). Oracle site has excellent details of the features.

Here, I present some examples and details to get started along with some of the important features and commands of this useful feature added in Java 9. Jshell is a quick way for developers to test code snippets. More details can be found at JEP 222 and jdk.shell site.

As indicated in JEP 222, the motivation of jshell is to interactively test expressions and code within the jshell state. The variables and methods that are going to be tested do not need to occur within a method/ class. All inputs to jshell must match the Java Language Specification (JLS). The jshell tool is not intended to be an IDE, hence, graphical support and debugger are not supported.

1. Introduction

Java 9 is a major release. While writing this article, JDK 9 is currently available for early access download on the oracle site and is expected to be released on July 27, 2017. This document attempts to summarize details of JDK9 REPL and some of the main features with this new release.
Complete list of features in Java 9 can be viewed at the oracle site.

Tip
You may skip setup sections if JDK 9 is already setup for you and jump directly to the features section below.

2. Getting started with Java 9

To download the currently available early access JDK or JRE 9, visit http://jdk.java.net/9/.

Accept license
Accept license

As shown in the image above, at the site, accept the license agreement and proceed to the download section as shown below.

Download JDK
Download JDK

Please select the appropriate OS and appropriate option for 32/ 64 bits for the OS to download the JDK/ JRE. It is also recommended to download the documentation along with the JDK/ JRE installation.

You may refer to this article to get started with Java 9 by executing a simple hello world program.

3. What is REPL?

REPL stands for read-eval-print-loop and is a shell interface for users to test code snippets. This shell interface reads the input, evaluates and prints the output (and errors if applicable). This is similar to the REPL tool available in Clojure/ Scala. This is a useful tool for testing small code snippets before moving into writing complete code in IDE.

From JEP222, jshell aims to provide an interactive tool to evaluate declarations, statements, and expressions of the Java programming language, together with an API so that other applications can leverage this functionality.

Code snippet written in jshell must correspond to any one of the below and must adhere to the Java Language Specification (JLS):

  • Expression
  • Statement
  • Class declaration
  • Interface declaration
  • Method declaration
  • Field declaration
  • Import declaration

3.1 Jshell /help

The following section Java 9 REPL features has details of the commands on jshell. Before we look at the commands, below is the introduction from jshell received by running /help intro on the jshell prompt.

jshell> /help intro
|  intro
|
|  The jshell tool allows you to execute Java code, getting immediate results.
|  You can enter a Java definition (variable, method, class, etc), like:  int x = 8
|  or a Java expression, like:  x + x
|  or a Java statement or import.
|  These little chunks of Java code are called 'snippets'.
|
|  There are also jshell commands that allow you to understand and
|  control what you are doing, like:  /list
|
|  For a list of commands: /help

Here are the shortcuts available in jshell:

jshell> /help shortcuts
|
|  shortcuts
|
|  Supported shortcuts include:
|
|  
|               After entering the first few letters of a Java identifier,
|               a jshell command, or, in some cases, a jshell command argument,
|               press the  key to complete the input.
|               If there is more than one completion, then possible completions will be shown.
|               Will show documentation if available and appropriate.
|
|  Shift- v
|               After a complete expression, hold down  while pressing ,
|               then release and press "v", the expression will be converted to
|               a variable declaration whose type is based on the type of the expression.
|
|  Shift- i
|               After an unresolvable identifier, hold down  while pressing ,
|               then release and press "i", and jshell will propose possible imports
|               which will resolve the identifier based on the content of the specified classpath.

Also, we can set an evaluation context to the jshell commands.

jshell> /help context
|
|  context
|
|  These options configure the evaluation context, they can be specified when
|  jshell is started: on the command-line, or restarted with the commands /env,
|  /reload, or /reset.
|
|  They are:
|       --class-path 
|               A list of directories, JAR archives,
|               and ZIP archives to search for class files.
|               The list is separated with the path separator
|               (a : on unix/linux/mac, and ; on windows).
|       --module-path ...
|               A list of directories, each directory
|               is a directory of modules.
|               The list is separated with the path separator
|               (a : on unix/linux/mac, and ; on windows).
|       --add-modules [,...]
|               root modules to resolve in addition to the initial module.
|                can also be ALL-DEFAULT, ALL-SYSTEM,
|               ALL-MODULE-PATH.
|       --add-exports /=(,)*
|               updates  to export  to ,
|               regardless of module declaration.
|                can be ALL-UNNAMED to export to all
|               unnamed modules. In jshell, if the  is not
|               specified (no =) then ALL-UNNAMED is used.
|
|  On the command-line these options must have two dashes, e.g.: --module-path
|  On jshell commands they can have one or two dashes, e.g.: -module-path

All the above can be used for the commands explained in the section below.

4. Java 9 REPL features

4.1 Getting started

To open JShell, go to the JDK installed bin directory and click on jshell:

jshell location in JDK directory
jshell location in JDK directory

This is how jshell prompt looks:

jshell
jshell

5. REPL examples

Let’s get started with some simple examples to get started with jshell.

5.1 Examples with expressions

Let’s start with basic java.lang.Math functions and System.out.println calls as shown in the snippets below. First we call Math.ceil method, followed by Math.floor method. These are standard methods in java.lang.Math class. /vars command lists all the variables set so far. This prints the two variables created when the Math methods were executed. System.out.println calls print the value being printed.

jshell> Math.ceil(10.1)
$1 ==> 11.0

jshell> Math.floor (11.6)
$2 ==> 11.0

jshell> /vars
double $1 = 11.0
double $2 = 11.0

jshell> System.out.println("Hello world")
Hello world

jshell> System.out.println ("with semi colon");
with semi colon

Examples with expressions
Examples with expressions

As you can see, we can run expressions on jshell and values of variables can be viewed using the /var command.

5.2 Examples with method

Let’s now move on to a complete method on jshell.

We are going to type a simple method that prints “Hello World”. The method is named printHelloWorld and makes a System.out.println call.

jshell> void printHelloWorld()
   ...> {
   ...> System.out.println("Hello World")
   ...> }

Examples with method
Examples with method

|  Error:
|  ';' expected
|  System.out.println("Hello World")
|                                   ^

Oops, we forgot a semi-colon! Let’s run it again with the semi-colon in place.

jshell> void printHelloWorld()
   ...> {
   ...> System.out.println("Hello World");
   ...> }

For quick typing, you may also hit tab button to get all possible completions.

jshell typing completions
jshell typing completions

Once this new method has been created, we can invoke it to see how it works.

jshell> printHelloWorld()
Hello World

jshell method
jshell method

5.3 Examples with variables

To test variables, let’s try the below commands that assign a value to variables i, j and then computes their sum (i+j). This is followed by printing i divided by j (i/j). Then, we assign two double variables d1 and d2 and compute d1 divided by d2 (d1/d2).

jshell> int i=10
i ==> 10

jshell> int j=20
j ==> 20

jshell> i+j
$10 ==> 30

jshell> i/j
$11 ==> 0

jshell> double d1 = 10
d1 ==> 10.0

jshell> double d2=20
d2 ==> 20.0

jshell> d1/d2
$14 ==> 0.5

Example with variables
Example with variables

As you can see, jshell is a simple tool to test out variables and variable assignment.

5.4 Example with class

To test a class on jshell, let’s try the below code that creates a class Employee with attributes empId, name, salary. The class has a parameterized constructor and overridden toString method.

jshell> public class Employee
...> {
...> String empId;
...> String name;
...> Integer salary;
...> public Employee (String empId, String name, Integer salary)
...> {
...> this.empId=empId;
...> this.name = name;
...> this.salary = salary;
...> }
...> public String toString ()
...> {
...> return "Employee [empId=" + empId + ", name=" + name + ", salary=" + salary + "]";
...> }
...> }

This gives the below output:

| created class Employee

Example with class
Example with class

In effect, as we have seen in the sections above, we can test any of the below in REPL: expressions, methods, variables, class.

6. Commands

6.1 /var command

To see all the variables created so far, type /var

/var command
/var command

6.2 /method command

To see all the methods created so far, type /method

/method command
/method command

6.3 /import command

To see all imports that are included by default, type /import

/import command
/import command

6.4 /save command

To save the history, type /save filename

/save command
/save command

6.5 /list and /history commands

To view the list of all snippets created and history of command input try /list and /history respectively.

/list and /history commands
/list and /history commands

6.6 /help command

To view all commands type /help

/help command
/help command

6.7 /reset command

To reset state, type /reset

/reset command
/reset command

6.8 /exit command

To exit, type /exit

7. When to use REPL?

REPL jshell is a great way to get started with JDK 9 without needing eclipse or a complete working environment. Simple expressions, methods and classes can be tested on command line. We expect this tool to be very useful for new developers.

However, whether REPL will replace IDEs like IntelliJ or Eclipse seems unlikely. Nevertheless, for new developers who need to try out some language features this could fit their needs well.

8. Summary

This article aims to provide a start to Java 9 REPL features. JDK 9 has some exciting new features and REPL promises to change how we currently write java code by allowing us to test as we go.

9. References

https://docs.oracle.com/javase/9/whatsnew/toc.htm
https://www.infoq.com/news/2016/09/JavaOne-2016-Keynote-JShell
http://openjdk.java.net/jeps/222

Sripriya Venkatesan

Sripriya is a Computer Science engineering graduate, she topped her graduation class and was a gold medalist. She has about 15 yrs of work experience, currently working as a technical architect/ technical manager for large scale enterprise applications, mainly around Java and database technologies; spanning different clients, geographies and domains. She has traveled to multiple countries and strives for work life balance. She is passionate about programming, design, architecture and enjoys working on new technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button