Sub topic 2
Managing a JShell Session with Slash Commands
This chapter assumes a JDK 9 or later, basic Java syntax, and terminal experience. JShell keeps declarations in a live session. Slash commands inspect or control that session.
Managing the session with slash commands
Commands start with /, so JShell does not treat them as Java code.
jshell> int total = 42
total ==> 42
jshell> /vars
| int total = 42
jshell> /list
1 : int total = 42;
jshell> /helpUse /methods to list declared methods. Use /drop total to remove a variable, or /drop 1 to remove a numbered snippet. /edit opens the current snippets in an editor. Tab completion helps complete names, methods, and commands.
Default imports and adding your own
JShell automatically imports common packages, including java.util.* and java.util.stream.*.
jshell> List<String> names = List.of("Ada", "Grace")
names ==> [Ada, Grace]
jshell> IntStream.rangeClosed(1, 3).sum()
$2 ==> 6
jshell> import java.time.LocalDate
jshell> LocalDate today = LocalDate.now()Use /imports to inspect imports currently active in the session.
Declaring methods
A method is a named operation. JShell accepts a method without requiring a surrounding class.
jshell> int square(int value) { return value * value; }
| created method square(int)
jshell> square(5)
$1 ==> 25
jshell> int square(int value) { return value * value * 2; }
| modified method square(int)
jshell> square(5)
$2 ==> 50The second declaration replaces the first method with the same signature.
Declaring classes, records, and interfaces
JShell also accepts top-level type declarations.
jshell> record User(String name) {}
| created record User
jshell> interface Labelled { String label(); }
| created interface Labelled
jshell> class Box { int size = 3; }
| created class BoxForward references and unresolved declarations
A method may refer to another method that has not been declared yet. JShell records the declaration but delays calls until the missing method exists.
jshell> int twice(int value) { return half(value) * 4; }
| created method twice(int), however, it cannot be invoked until method half(int) is declared
jshell> int half(int value) { return value / 2; }
| created method half(int)
jshell> twice(10)
$3 ==> 20Exercise
Which command lists variables, and which command removes one?
Show answer
/vars lists variables. /drop name removes a variable by name.