JShell (Java REPL) in Java 9

In Java 9, a new feature called JShell, which stands for Java Shell, was introduced. JShell is a Read-Eval-Print Loop (REPL) tool that allows you to interactively evaluate Java expressions and statements. It provides a convenient way to experiment with Java code without the need for compiling and running a complete Java program.

Getting Started with JShell

To start the JShell tool, open a terminal or command prompt and type jshell. The JShell prompt (jshell>) will appear, indicating that you can start entering Java expressions and statements.

Let’s try a simple example. Type the following:

jshell> int x = 5;
jshell> int y = 10;
jshell> int sum = x + y;
jshell> sum

JShell will output the result of the sum expression, which should be 15.

Features of JShell

Immediate Feedback

One of the main benefits of JShell is that it provides immediate feedback. As you enter expressions and statements, JShell evaluates them and displays the results immediately. This makes it easy to experiment and quickly see the output without having to write a whole program.

Tab Completion

JShell supports tab completion, which helps in writing code faster and reduces the likelihood of errors. When you start typing a class, method, or variable name, JShell will provide suggestions and let you choose the desired option by pressing Tab.

Command History

JShell keeps a history of the commands you have entered, allowing you to recall and reuse previous commands. You can navigate through the command history using the Up and Down arrow keys.

Import Declarations

JShell automatically imports commonly used packages, such as java.util, java.nio, and java.lang, so you can use classes from these packages directly without the need for import statements. If you need to import other packages or classes, you can do so using the import command.

Snippets and Variables

JShell introduces the concept of snippets. A snippet is a sequence of code entered into JShell. Each snippet is assigned an identifier (e.g., $1, $2, etc.), which can be used to reference it later. Variables defined within a snippet are accessible only within that snippet.

Exception Handling

JShell provides exception handling for individual statements. If an exception occurs during the evaluation of a statement, JShell will display a descriptive error message along with the stack trace, allowing you to quickly identify and fix the issue.

Conclusion

JShell is a powerful tool for quickly testing and experimenting with Java code. It provides a convenient and interactive way to evaluate expressions and statements without the need for writing a complete program. With features like immediate feedback, tab completion, and command history, JShell enhances the development experience and productivity of Java programmers.

References

#hashtags #JShell