Sub topic 5
Managing the Session with Slash Commands
This chapter assumes that you have a JDK 9 or later, the jshell command on your PATH, basic Java syntax, and terminal experience. JShell slash commands manage the current session. They inspect variables and methods, show previous input, remove definitions, and provide help. They are commands to JShell, not Java code, so they begin with / and do not use semicolons.
Inspecting Session State
As you enter declarations and expressions, JShell keeps them in the current session. Use these commands to inspect that state:
| Command | Purpose |
|---|---|
| `/vars` | Lists variables currently defined |
| `/methods` | Lists methods currently defined |
| `/list` | Shows snippets entered during the session |
| `/types` | Lists classes, interfaces, enums, and records |
| `/help` | Shows available commands and command syntax |
For example:
jshell> int width = 8
width ==> 8
jshell> int area(int side) { return side * side; }
| created method area(int)
jshell> /vars
| int width = 8
jshell> /methods
| int area(int)
jshell> /list
1 : int width = 8;
2 : int area(int side) { return side * side; }/list displays the source of snippets, including declarations and expressions. This is useful when you remember that something worked but not the exact input. The numbering identifies snippets in the current session.
Removing Definitions
Use /drop when a variable or method is no longer useful:
jshell> /drop width
| dropped variable width
jshell> /varsYou can usually identify a snippet by its name or by its number. For example, /drop 2 removes snippet 2. Removing a variable does not undo every later operation that used it. It only removes that definition from the session.
If a name is causing confusion, remove it before declaring a replacement. You can also use /reset to discard the entire session state and start again. Because /reset removes all variables, methods, imports, and types, check your work before using it.
Finding Command Syntax
Use /help when you do not remember a command:
jshell> /help dropUse /help by itself for the complete command list. /help intro displays JShell's introductory guidance. The exact formatting of help output can vary between JDK versions, but the command names and general behavior remain consistent.
The session-management workflow is:
Exercise
Exercise
Define a variable named count and a method named doubleCount, use slash commands to inspect both, then remove the variable without removing the method. Which commands do you use?
Show answer
Enter int count = 4 and int doubleCount(int x) { return x * 2; }. Run /vars and /methods to inspect them, then run /drop count. The method remains defined.