Introduction to Java REPL

Running a code right away without having to start the whole IDE and creating a project from scratch can be very convenient. It allows you to have numerous applications like prototyping, trying out new functions, testing and debugging or running a small module from a bigger project. This can be easily done using a Read Evaluate Print Loop (REPL). An REPL works on a shell interface that reads each line of entered code individually, evaluates it, and then prints the result instantly. It evaluates all the declarations, statements, and expressions as they are entered and immediately shows the results. It is interactive and executes the code without any delays. Many programming languages previously did not have an REPL and Java was one of them for quite some time. Arguably, Java REPL was introduced very late. With the release of Java 9 in 2016, Java got a fully functional REPL environment called JShell.

This post will provide a complete introduction and a comprehensive guide to JShell, explaining all its commands and its most effective usage in Java programming. 

What is JShell?

The Java Shell or JShell is an official Java REPL. It provides an interactive shell for rapid prototyping, testing and debugging for running Java APIs and for learning Java programming. All can be done without using a public static void main method or compiling the code before execution just by writing the code on a basic command-line interface. JShell is exceptional in providing intermediate feedback. All the time that is taken by IDEs while debugging or testing is saved, thanks to JShell. It has become even simpler and practical with the introduction of the var keyword in Java 10.

Starting with the basics

JShell can be easily started by just typing “jshell” on the command line. It will then present a welcome message and shell will be ready for you to input your commands or any Java expression.

$ jshell
|  Welcome to JShell -- Version 10.0.2
|  For an introduction type: /help intro 

The version of JShell can vary based on the Java version you are using but make sure to use version 10 or the latest one (Java 11 SE) because the var keyword frequently used in this guide was introduced in Java 10.

Now you can start entering the code. For example, type var statement = “JShell is a java repl” At the shell prompt, press enter, and you should see the following output:

jshell> var str01 = "Jshell is a java repl"
str01 ==> "Jshell is a java repl"

Here, you must have noticed that you do not need to end all the expressions with a semicolon like you normally do in Java. JShell here also echoes the value of the variable statement and confirms that its value is now equal to “Jshell is a Java repl”.

In case you have not completed your expression and unintentionally press enter, JShell will recognize that you are not finished with your expression and will allow you to continue on the next line. See the code below:

jshell> var str02 =
  ...> "repl java"
Statement02 ==> "repl java"

Errors in JShell

There are obvious chances of making errors in JShell like we make while coding. In IDEs, you can easily find the mistakes you have made. Similarly, if you happen to make a mistake or enter an invalid expression, command method or expression in a Java REPL, it provides you with immediate feedback by displaying an error and underlining the problem.

1.	jshell> student.calGrade(85,2)
2.	|  Error:
3.	|  cannot find symbol
4.	|    symbol:   method calGrade(int,int)
5.	|  student.calGrade(85,2)
6.	|  ^--------------------^

Methods and classes

Being an OOP programming language, classes are an integral part of Java and so are methods. To create classes or methods in JShell, you need to just write the code line-by-line. If everything goes right, JShell will echo that it has successfully created the method or class which is ready to be used.

See this code below: 

1.	jshell> public class A {
2.	  ...> private String name
3.	  ...> public String getName() {
4.	  ...> return this.name
5.	  ...> }
6.	  ...> }
7.	|  created class A

Java REPL also allows methods to utilize yet-to-be-defined variables, for instance, when you define a new method called getAge() that returns the age. However, we will reference an undefined variable called age.

1.	jshell> public String getAge() {
2.	  ...> return age;
3.	  ...> }
4.	|  created method getAge(), however, it cannot be invoked until variable age is declared

See, JShell has created the getAge() method but it notifies that it cannot be used until we declare or define the age variable. 

Creating classes or methods in Java REPL can often be a difficult process. There are no options for formatting so you will just have to keep typing your code line by line. This makes it very frustrating in case you make an error, as you will not be notified by JShell until you complete the class.

Scratch variables

Along with variables (var) that can be explicitly declared and defined by the user, JShell also automatically creates variables for unassigned expressions. These are called scratch variables. They follow a common pattern, starting with a dollar sign, and a number that is increasing incrementally.

You can refer to them just like any other variable. For example, see this code below; here a method called getName() is called and its result is utilized as an argument to System.out.println,

1.	jshell> getName()
2.	$14 ==> "Harry"
3.	jshell> System.out.println($14)
4.	Harry

JShell commands

We have discussed some highly common JShell expressions. There are many more that also exist, but JShell comes with some built-in commands that can be a great help in numerous scenarios.

To see the complete list of all possible commands, you can type /help at the prompt.

1.	jshell> /help
2.	|  Type a Java language expression, statement, or declaration.
3.	|  Or type one of the following commands:
4.	|  /list [<name or id>|-all|-start]
5.	|       list the source you have typed
6.	|  /edit <name or id>
7.	|       edit a source entry
8.	|  /drop <name or id>
9.	|       delete a source entry
10.	(shortened for brevity)

If you want to learn about a particular command you can type /help <command>, where <command> is replaced with the name of that command like this:

1.	jshell> /help list
2.	|
3.	|                                   /list
4.	|                                   =====
5.	|
6.	|  Show the snippets, prefaced with their snippet IDs.

Following are all the commands in Java Repl with their brief description:

Command            | Description
--------------------|------------------------------------
 /!                 | Rerun last snippet
 /-              | Rerun the last -th snippet
 /              | Rerun specific snippet                     
 /list              | List source of session
 /vars              | List variables
 /types             | List types
 /methods           | List methods
 /imports           | List imports                     
 /history           | Plain text history
 /drop  | Delete source entry
 /edit              | Open all source in editor
 /edit          | Open specific source in editor
 /open        | Open file as source input
 /save        | Save snippets to                      
 /reload            | Reset and replay each snippet
 /reset             | Reset JShell
 /env               | View or change the evaluation context
 /set   | Configure JShell
 /exit              | Quit JShell

Some effective uses of Java REPL

JShell is a remarkable Java REPL. We have just covered the tip of the iceberg but to get the most out of JShell, you should discover it more by yourself and understand some of its most effective uses. It is an extremely useful tool for new developers to learn Java as a language before jumping into any specific field. You can learn and improve your knowledge of the Java language. You can easily work around with new APIs on JShell both inside and outside of the JDK without dealing with any IDEs or configurations. Nonetheless, the best use of this Java REPL is for quick prototyping of any idea or a concept that you want to find the potential of without spending much time or effort on it.

See Also: Java Getters and Setters: Basics, Common Mistakes, and Best Practices

Author

Shaharyar Lalani is a developer with a strong interest in business analysis, project management, and UX design. He writes and teaches extensively on themes current in the world of web and app development, especially in Java technology.

Write A Comment