JShell – Java 9 interpreter (REPL) – Getting Started

What is REPL

Many languages include tools (sometimes called REPL) for statements interpretation. Using these tools you can test code snippets quickly without creating full project.

For example python. Creating project can sometimes take a long time, but using repl you can getting started with the language more quickly. Each entered expression gives you returned value and it’s type – that’s very valuable information.

In java, instead, we have to create a test or main method which prints results and needs to be recompiled every time you make a change.

What is JShell

The JShell tool is a command line tool (which will be introduced in Java 9 realease) that facilitates exploratory programming by providing interactive use of Java Programming Language elements. JShell is a REPL (Read-Evaluate-Print-Loop). It is ideal both for learning the Java language and exploring unfamiliar code (include new Java APIs). Typical Java development means writing a complete program, then compiling it (fixing any errors), the running it, figuring out what is wrong, editing, and repeating. With JShell you can enter program elements one at a time, immediately seeing the result and adjusting accordingly. During development, code can be pasted into JShell, and/or working code pasted from JShell into a program editor.

Starting JShell

First install JDK 9. JShell is included in JDK 9. You can get early access build on http://jdk.java.net/9/.
For this tutorial all examples use verbose mode. To launch the JShell tool in verbose mode, type jshell at the command-line:

Expressions and statements

JShell accepts Java statements, variable, method, and class definitions, imports, and expressions. For example, you can enter a statement at the prompt, any side-effects will take place and any output displayed:

By default, JShell will give you information about what you entered. Here for example, declaring a variable:

When an expression is entered that doesn’t have a named variable, a scratch variable is created so that the value can be referenced later :

Methods

commands

JShell has a number of commands for controlling the environment and displaying information. They are distinguished from snippets by a leading slash.

list of variables

list of methods

list of entered snippets

exit from jshell

Tab Completion -Commands

Tab completion works for commands and command arguments as well:

 

Leave a Reply

Your email address will not be published.

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