Java REPL - jshell With Examples

Java REPL or jshell is the new tool introduced in java 9. Today we will look into Java REPL basics and run some test programs in jshell interface.

Java REPL

Let’s first try to understand why REPL support was added in Java, if it was that important then why in so late release.

As you know, Scala has become very popular to develop from small to large-scale applications because of it’s features and advantages. It supports multi-paradigm (Object-Oriented and Functional Programming) and REPL.

Oracle Corporation is trying to integrate most of Scala features into Java. They have already integrated some functional programming features as part of Java 8, such as lambda expressions.

Scala’s one of the best features is REPL (Read-Evaluate-Print-Loop). It’s a command line interface and Scala Interpreter to execute Scala programs. It’s very easy to use Scala REPL to learn basics of scala programming and even run small test code.

Because of Scala REPL and it’s benefits in reducing the learning curve and ease of running test code, Java REPL got introduced in java 9.

Java REPL – jshell

Java REPL application name is jshell. JShell stands for Java Shell. jshell is an interactive tool to execute and evaluate java simple programs like variable declarations, statements, expressions, simple Programs etc.

Open command prompt and check java version to make sure you have java 9 or above, then only you can use jshell.

java-repl-jshell-java-9

Since jshell don’t need any IDEs or extra editors to execute simple java programs, It’s very useful for beginners in core java and experts to use it to learn and evaluate new features and small test code.

Java REPL – jshell basics

We can access Java REPL by using jshell command available as shown in below image.

java-repl-jshell

Now, it’s time to execute few simple java examples to get the taste of java REPL tool.

As shown in the above Java REPL examples, it’s very easy to develop “Hello World” program. We don’t need to define “public class” and public static void main(String[] args) method just to print one message.

NOTE: We don’t need to use “semicolons” for simple statements as shown in the above diagram.

Java REPL – execute class

We can also define and execute class methods in Java REPL shell.

Java REPL – Help and Exit

To get jshell tool help section, use /help command. To exit from jshell, use command /exit.

We can also use Ctrl + D command to exit from jshell tool.

That’s all about Java REPL and jshell tool basics, read more at jshell – java shell.

Reference: JEP 222

By admin

Leave a Reply