Java JShell: All You Need to Know

310 VIEWS

As a programmer, you will often find yourself testing code snippets before integrating them into a larger codebase. For this reason, programming languages such as Python and JavaScript are widely adopted and easy to use, as they offer a REPL, where you can do single input testing of smaller segments of code. For a long time, Java did not provide a REPL tool. Programmers had to go through the ordeal of creating a class and several other follow-ons just to print a simple “Hello World” screen.


Java addressed the issue in the Java 9 release by adding Java JShell, a Java REPL. A motivation for this move was to reduce Java’s learning curve and retain its adoption by schools, and at the same time, facilitate faster prototyping. Stanford, for instance, replaced Java with JavaScript in some introductory courses, although for a slightly different reason. Beyond that, JShell makes learning Java easier for newbie programmers. Here is what you need to know about JShell to increase your productivity.

Installation
JShell is not stand-alone. It comes bundled with JDK 9. Here’s how to install it on Ubuntu:
$ sudo add-apt-repository -y ppa:webupd8team
$ sudo apt update
$ sudo apt install oracle-java9-installer
Windows, Mac, and other Linux distro users can obtain the JDK and JRE here. Note that you can set Java 9 as your default Java, but I do not include that here, as JShell is the only tool in focus here.

Diving In
The syntax for expressions, method, import, class, and interface declaration is no different from the usual Java syntax. The only difference here is that you get immediate feedback. Pretty much everything Java can be done with JShell, as it is built on top of the JDK. To start JShell, open up the command line and type jshell. You can go ahead and try some code—and get some instant feedback!

bruno@thBashShell ~ $ jshell
|  Welcome to JShell — Version 9-internal
|  For an introduction type: /help intro


-> double randomNumber = Math.random()
|  Added variable randomNumber of type double with initial value 0.6619623393268026

-> void say() {
>> printf(“It works!”);
>> }
|  Added method say()

JShell has a list of useful commands. Typing /help will list all those commands. I will only highlight a few, as /help provides succinct info to tinker with all the commands.

/open <file>  – open the specified file and execute it. If you have a file named foo, which contains the following code:
    for (int i = 0; i < 30; )
           System.out.println(i++);
executing /open foo will print out 0 to 29.

/save [all|history|start] <file>  – Save your work to the specified file. When used without any option, every entry except the JShell commands is saved.

/exit  – Exit JShell. Command line programs can be infamous when it comes to exiting. For newbies, it seems a dead end unless there is a window exit button. On Linux, an alternative is to use Ctrl + D.

/methods  – List all methods entered. The printf method is displayed as it is automatically added at startup.

/vars   – List all variables.

Thanks to JShell’s command completion feature, you don’t need to fully type out these commands. Just typing /m, /me, or /meth is sufficient to be interpreted as /methods. There’s a little caveat here: This only works if what is after the forward slash uniquely identifies a command. So JShell will spew out “Command: ‘/s’ is ambiguous: /save, /set” if you enter /s. If you meant /save, /sa will suffice; you should use /se if /set is what you wanted.

Beyond this, there are many cool features worth knowing.


Tab Completion
You will struggle to find a programmer who hasn’t enjoyed the convenience of tab completion at some point in their career. Thankfully, JShell supports tab completion for commands.
Begin typing import java.security, followed by TAB and you get a complete list of all classes under java.security. The TAB key can be used on an import hierarchy until there is nothing more to complete. Tab completion works in other places as well, like method calls.

Semicolon Omission
If you have used languages that require a semicolon to signal the end of a statement, you probably have erred on that requirement several times. Many IDEs do fair work in spotting such violations, but we keep making them either way. JShell does not require a semicolon in several one-line statements. However, semicolons are absolutely required in some cases, such as in methods.

Keyboard Shortcuts
The up and down arrow keys are used to cycle through the history just as in most shells. The right and left arrow keys move a character to the right or left respectively.


Ctrl + A will move the cursor to the beginning of the line.
Ctrl + E will move the cursor to the end of the line.
Ctrl + K will delete everything on the line after the cursor.

Forward Referencing
Once in awhile you will catch yourself using a variable in a method before its declaration. This yields a compilation error. JShell allows this. However, the variable must be declared before the method is used. JShell will warn you in advance: “Added method foo(), however, it cannot be invoked until variable message is declared.” (Mind you, you can only do this in JShell.)

JShell API
APIs allow for quick innovation. For businesses, they can quickly become a steady stream of revenue or an opportunity to reach customers in diverse ways. JShell has an API, opened to all for any form of innovation. I foresee IDEs integrating JShell into their platforms.

Final Thoughts
The arrival of a Java REPL was definitely long overdue, but it is better late than never. JShell does exactly what many REPLs do—make coding less cumbersome. Although I do not anticipate the sole use of JShell for large projects, it may become programmers’ “scratchpad.” for the Java programmer, JShell is a must-have tool in your toolbox. Have fun!

Do you think you can beat this Sweet post?

If so, you may have what it takes to become a Sweetcode contributor... Learn More.

Bruno is a junior at Ashesi University College studying Computer Science. He is interested in leveraging the power of technology to increase productivity. As a big fan of open source technology, he is currently exploring the possibility of using the Bitcoin Blockchain to fight corruption in government.


Discussion

Click on a tab to select how you'd like to leave your comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Menu