The basic unit of code used by JShell is the snippet, or source entry. Every time you declare a local variable or define a local method or class, you create a snippet whose name is the identifier of the variable/method/class. At any time, you can edit a snippet you have created with the /edit
command. For example, let's say I have created the class Foo
with a single, method, bar
:
jshell> class Foo {
...> void bar() {
...> }
...> }
Now, I want to fill in the body of my method. Rather than rewrite the entire class, I can edit it:
jshell> /edit Foo
By default, a swing editor will pop up with the most basic features possible. However you can change the editor that JShell uses:
jshell> /set editor emacs
jshell> /set editor vi
jshell> /set editor nano
jshell> /set editor -default
Note that if the new version of the snippet contains any syntax errors, it may not be saved. Likewise, a snippet is only created if the original declaration/definition is syntactically correct; the following does not work:
jshell> String st = String 3
//error omitted
jshell> /edit st
| No such snippet: st
However, snippets may be compiled and hence editable despite certain compile-time errors, such as mismatched types—the following works:
jshell> int i = "hello"
//error omitted
jshell> /edit i
Finally, snippets may be deleted using the /drop
command:
jshell> int i = 13
jshell> /drop i
jshell> System.out.println(i)
| Error:
| cannot find symbol
| symbol: variable i
| System.out.println(i)
|
To delete all snippets, thereby reseting the state of the JVM, use \reset
:
jshell> int i = 2
jshell> String s = "hi"
jshell> /reset
| Resetting state.
jshell> i
| Error:
| cannot find symbol
| symbol: variable i
| i
| ^
jshell> s
| Error:
| cannot find symbol
| symbol: variable s
| s
| ^