JShell the Java REPL - Sip of Java

Do you want to try something out in Java? Or experiment with a new feature or API? But don’t want to have to go through the ceremony of creating an application? Then you should consider JShell, Java’s REPL! Let’s look at it in this article.

JShell

JShell, added in JDK 9, is Java’s REPL, which stands for Read, Evaluate, Print, Loop. This means JShell can read a Java snippet, evaluate it, print the result, and loop back to the command prompt. This makes it an excellent tool for experimenting with and learning about Java.

To use JShell, from a terminal, run the command: jshell.

Using JShell

JShell can evaluate a Java snippet without going through the ceremony of defining a class or even a method. Like in this example where we do some simple math:

jshell> 2+2
$1 ==> 4

Using Variables

When a Java snippet has a return value, like in the previous example, JShell will automatically assign it to a variable, in this case, $1. This can then be referenced for later use:

jshell> System.out.println($1 * 2)
8

💡 Note how eight isn’t assigned a value because System.out.println(String) doesn’t have a return value!

Manually Declaring Variables

Variables can be manually declared as well:

jshell> int x = 10
x ==> 10

Multi-line Snippets and Saving Methods and Classes

JShell isn’t just limited to single-line Java snippets, it can evaluate multi-line snippets as well:

jshell> public void helloMessage(String msg){
   ...>     System.out.println("Hello " + msg);
   ...> }
|  created method helloMessage(String)

When a method or class is defined, like a variable, it will be saved and can be referenced later:

jshell> helloMessage("Java Developers!")
Hello Java Developers!

JShell Commands

JShell has several built-in commands. These commands can be accessed by prepending a backslash /. Key commands are:

  • /exit - Exits JShell
  • /vars - Lists stored variables
  • /help - Displays help message
jshell> /exit
|  Goodbye
$

Additional Reading

Happy coding!