Sub topic 11
Tab Completion and Editing with `/edit`
Assume you already know how to start JShell, declare variables, and enter snippets. This chapter shows how to correct and explore code faster inside a running session.
Complete names with Tab
JShell provides context-aware completion. Press Tab after part of a command, type, variable name, method name, or member access. JShell may insert the completion or display matching choices.
For example, start a session and define a value:
jshell> String message = "hello"
message ==> "hello"
jshell> message.toU<Tab>The terminal can complete toU to toUpperCase. Press Enter after the completion is inserted:
jshell> message.toUpperCase()
$2 ==> "HELLO"Completion also helps with types and variables:
jshell> Str<Tab>
String
jshell> mess<Tab>
messageThe exact display depends on your terminal and JDK version. If several names match, press Tab again or add more characters to narrow the choices.
Completion can reveal methods that you may not remember. After typing message. and pressing Tab, inspect the available members. This is useful for learning an API, but it does not replace reading the method's documentation. Completion usually shows names and signatures, not the method's intended behavior.
Correct snippets with `/edit`
For a longer expression or method, repeated arrow-key editing becomes inconvenient. The /edit command opens JShell input in an external editor.
jshell> int cube(int x) {
...> return x * x * x;
...> }
| created method cube(int)
jshell> /edit cubeJShell opens the source for cube in the configured editor. Correct the source, save it, and close the editor. JShell then submits the edited snippet and reports whether it created or modified the method.
You can also edit a snippet by its number when /list shows its identifier:
jshell> /list
1 : int cube(int x) {
return x * x * x;
}
jshell> /edit 1If /edit does not open the editor you expect, configure one with /set editor. The command must be available on your system. For example:
jshell> /set editor nano
jshell> /edit cubeOn another machine, use an installed editor such as vim or a graphical editor command.
Choose the right editing method
Use Tab for discovery and short completions. Use normal line editing for a small typo. Use /edit when a method, class, or multiline declaration needs several changes.
A common mistake is editing a snippet without checking what JShell will resubmit. Use /list first when the session contains several similar declarations. After saving, test the changed declaration with a representative call.
Exercise
Which approach is most suitable for correcting a typo in a long multiline method: pressing Tab, using arrow keys, or /edit?
Show answer
Use /edit, because it opens the stored snippet in an external editor where multiline changes are easier to review.