JShell is an interactive Java prompt. You type a line, it works out the answer, and it prints the answer for you. There is no class declaration, there is no main method, and there is no compile step in the middle. That removes almost all of the friction between the question "what does this expression do" and the answer.
The previous lesson in this module covered "What Is the Difference Between JDK, JRE and the JVM?", and this is the last lesson in the module. The next module starts with "What Are Java's Primitive Data Types and When Do You Use Each?", which moves on from running Java to writing it.
How do I start a session?
Run jshell in a terminal and you get a prompt that waits for your input.
jshell
| Welcome to JShell -- an enhanced REPL for Java.
| For an introduction type: /help
jshell> 1 + 1
$1 ==> 2
jshell> String name = "Ada";
$2 ==> "Ada"
jshell> name.toUpperCase()
$3 ==> "ADA"
jshell> /exit
Two details carry most of the value. First, an expression on its own is worked out and displayed, and the answer is also given to a hidden variable so that you can use it later. Those variables are called $1, $2 and so on. Second, a declaration is echoed back to you, which is a cheap way to confirm that the type you got is the type that you expected.
Why is it faster than writing a class?
Compare the two ways of doing the same job. To find out what List.of does when you give it the same value twice, the class route means creating a file, writing a class, writing a main method, writing a print statement, compiling it and running it. The JShell route is one line.
jshell> import java.util.List;
jshell> List.of(1, 2, 3)
$1 ==> [1, 2, 3]
jshell> List.of(1, 1)
| Exception java.lang.IllegalArgumentException: duplicate element: 1
For anything exploratory, such as what a method returns, how a collection behaves, or even whether an expression compiles at all, that difference is the difference between a two minute detour and a two second one.
When something goes wrong, the prompt stays alive. That is the second big advantage, because an exception is information and not a crash, so you can look at the state that produced it straight away.
Can I define methods and classes in the prompt?
Yes, and this is where JShell stops being a calculator. A method definition ends at the closing brace, and the shell keeps it for the rest of the session.
jshell> int area(int width, int height) {
...> return width * height;
...> }
| created method area(int, int)
jshell> area(3, 4)
$1 ==> 12
Classes work in exactly the same way, and a class that you define in one session stays visible for the rest of that session. That means you can sketch a small design interactively before you commit it to real files.
Which commands are worth knowing?
- The command
/helplists every command, and/help <command>explains one of them. - The command
/envshows the current class path and the other settings. - The command
/importslists everything that has been imported so far, which saves you a lot of guessing when an import is missing. - The command
/reloadreads the files of the session again, so you can edit a class on disk and see the change without starting again. - The command
/resetclears the session and starts over, while keeping the class path. - The commands
/saveand/opencapture a session into a file and replay it later, which turns a throwaway exploration into a replayable script. - The command
/exitleaves the prompt.
How do I use my own classes?
Put your compiled classes on the class path and the shell can import them like any other library class.
# compile your project
javac -d out src/com/example/Util.java
# start the shell with that output on the class path
jshell --class-path out
# or start it with a source file directly
jshell src/com/example/Util.java
jshell> import com.example.Util;
jshell> Util.duplicate("ab")
$1 ==> "abab"
This is the pattern that makes JShell worth the minute that it takes to learn. You compile a class once and then you question it while you type. You keep the real implementation and you throw away the throwaway test harness.
Where does JShell fit in a normal working day?
It is tempting to treat JShell as a toy, because it feels like a calculator. It is more useful than that, and the pattern that makes it worthwhile is simple. Keep the real code in files, and use the shell as a probe for the code that you have just written.
Suppose you have written a parsing method and you are not sure how it behaves on an awkward case. Instead of writing a throwaway class with a main method, compiling it and deleting it afterwards, you put the compiled class on the class path and you ask the shell directly.
jshell> import com.example.Parser;
jshell> Parser.parse("")
$1 ==> []
jshell> Parser.parse("a,b,,c")
$2 ==> [a, b, c]
jshell> Parser.parse(null)
| Exception java.lang.IllegalArgumentException: input must not be null
Look at what happened there. You discovered that an empty piece is dropped without a word, and that a null input throws a specific exception. Both of those details are much cheaper to find here than they are in production.
What should you not use it for?
Two limits are worth keeping in mind. The shell is not a place to build a program, because anything longer than a few methods belongs in a file where it can be reviewed, compared and tested. And a session does not last, because when the process ends everything that you typed is gone unless you saved it. That is why the command /save exists, because a saved session is a script that you can run again.
# capture a session into a file, then replay it later
jshell session.jsh
jshell --class-path out session.jsh
Used that way, the shell becomes a documentation tool as much as an exploration tool. The transcript shows the inputs, the outputs and the errors, and that is exactly what a reader needs in order to understand what a piece of code does.
Quick reference
- The command jshell starts the prompt, and the command
/exitleaves it. - Expressions are worked out for you, and their answers are held in
$1,$2and so on. - Methods and classes can be defined inside the session and they stay available.
- The command
/reloadreads the files again,/resetclears the session, and/envshows the class path. - The option
--class-pathputs your own compiled classes within reach. - An exception does not end the session. Read the message, look at the state and carry on.
Try it yourself: start JShell and work through three experiments. Build a HashMap and print it. Call a method that throws and catch the exception. Then define a small class and make an object from it. When you are done, use /save to capture the session, and then run it again later with /open so that you can watch the whole thing replay.