Java 9 – JShell and REPL

1. Overview

How many times we had created new class with the main method just to write and execute a little snippet of code to test some feature? In Java9 this is now a simple operation with the introduction of JShell.

2. What is JShell?

JShell is a Java read-eval-print loop (REPL) tool first introduced in the JDK 9. REPL allows to interactively run arbitrary snippets of code and evaluate their results. This allows us to quickly check the viability of an idea like formatting the string or checking date formats.

3. Running

To get started we need to run the JShell, which is done by invoking the below command

Here we used -v (verbose mode) option to get the detailed messages.

4. Lets try few commands

4.1. Check default imports

4.2. Variables

Variables can be defined with the normal Java declaration syntax. Once we do that they become visible in the scope.

4.3. Defining and Invoking Methods

We can define methods, invoke and also replace them.

4.4 Commands

Jshell provides quite a few meta-commands that aren’t related to evaluating Java statements. Commands starts with a forward-slash (/). To get the list of all available commands issue /help or /?.

Let’s take a look at some of them.

4.5 Saving and Loading

To save the commands/ expression history, we need to use /save command. And, to load a previously saved file we can use the /open command. A loaded session can then be verified by issuing /var, /method or /list etc.,.

4.6 Exiting

Issue /exit command can terminate the shell.

5. Conclusion

In this article, We looked at JShell and ran few commands. JShell is a very useful tool for prototyping and testing Java code snippets. A valuable tool in java tookit added :).

harinathk
 

Click Here to Leave a Comment Below 0 comments