created on | January 28, 2022 |
jshell accepts the following JLS syntax:
These pieces of Java code are referred to as snippets in jshell slang. Contrary to the usual Java syntax, statements, expressions, etc. do not have to end with a semicolon, except in class and interface definitions.
To change the definition of a variable, method, or class that was previously entered, simply the new definition is entered.
jshell allows the definition of methods whose bodies reference methods, variables, or classes that are not yet defined. jshell accepts the definition but warns of what is yet to be defined. The definition may be referenced, but any execution before the missing references have been defined will fail.
On the other hand, classes have to be defined before they can be referenced.
All snippets that have been entered during a session can be listed with . The snippets are preceded by their id (consecutive numbers):
To list all snippets that are loaded on startup of the jshell (by default, this is some imports), use :
To list all snippets of a session, use . This includes the snippets loaded on startup and all entered snippets, no matter if any of those snippets (or their respective method, class or interface definitions) have been dropped. We’ll come to the dropping of snippets, that is removing snippets from a session, shortly.
As you can see in the example above, ids of snippets loaded on startup start with the letter ’s', followed by a consecutive number.
Snippets are referenced by:
Snippets that have been entered can be edited by browsing through the snippet history with the up/down keys until you hit the snippet you want to edit and edit it. For oneliners like an expression the jshell’s editing capabilities are sufficient.
However, method, class and interface definitions usually consist of several lines, editing them in the jshell is next to impossible. But snippets can also be edited with . By default, this invokes the jshell Edit Pad, which is a rather simplicistic editor.
The jshell Edit Pad is sufficient for simple editing, but it pays off to set a default editor like nano or joe with the command:
To drop a snippet is to remove it from the current session. After a snippet has been dropped, anything defined in that snippet (i.e. a method or a class) is no longer available in the session. Snippets are dropped with the command. The command accepts the snippets id as well as the snippets name as the parameter. To drop a previously defined class Fruit, you can enter :