JSHELL(1)
π» jshell(1) β JDK Commands π¦
πΈ NAME πΈ
okay so jshell is the tool that lets you interactively evaluate declarations, statements, and expressions of the Java programming language in a read-eval-print loop (REPL) β it's giving βJava, but make it a conversationβ π
β¨ SYNOPSIS β¨
jshell [options] [load-files]
optionsβ command-line options, separated by spaces. see Options for jshell.load-filesβ one or more scripts to run when the tool is started. scripts can contain any valid code snippets or JShell commands.
the script can be a local file or one of these predefined scripts, bestie:
DEFAULTβ loads the default entries, which are commonly used as imports.JAVASEβ imports all Java SE packages.PRINTINGβ definesprint,println, andprintfas jshell methods for use within the tool.TOOLINGβ definesjavac,jar, and other methods for running JDK tools via their command-line interface within the jshell tool.
for more than one script, use a space to separate the names. scripts are run in the order in which they're entered on the command line. command-line scripts are run after startup scripts. to run a script after JShell is started, use the /open command.
to accept input from standard input and suppress the interactive I/O, enter a hyphen (-) for load-files. this option enables the use of the jshell tool in pipe chains π«Ά
π¦ DESCRIPTION π¦
JShell provides a way to interactively evaluate declarations, statements, and expressions of the Java programming language, making it easier to learn the language, explore unfamiliar code and APIs, and prototype complex code. Java statements, variable definitions, method definitions, class definitions, import statements, and expressions are accepted. the bits of code entered are called snippets β¨
as snippets are entered, they're evaluated, and feedback is provided. feedback varies from the results and explanations of actions to nothing, depending on the snippet entered and the feedback mode chosen. errors are described regardless of the feedback mode. start with the verbose mode to get the most feedback while learning the tool β highly recommend, no cap π―
command-line options are available for configuring the initial environment when JShell is started. within JShell, commands are available for modifying the environment as needed.
existing snippets can be loaded from a file to initialize a JShell session, or at any time within a session. snippets can be modified within the session to try out different variations and make corrections. to keep snippets for later use, save them to a file π
π OPTIONS FOR JSHELL π
--add-exports module/packageβ specifies a package to be considered as exported from its defining module.--add-modules module[,module...]β specifies the root modules to resolve in addition to the initial module.-Cflagβ passes flag to the Java compiler inside JShell. for example,-C-Xlintenables all the recommended lint warnings, and-C--release=<N>compiles for Java SE N, as if--release Nwas specified.--class-path pathβ specifies the directories and archives that are searched to locate class files. this option overrides the path in theCLASSPATHenvironment variable. if the environment variable isn't set and this option isn't used, then the current directory is searched. for Linux and macOS, use a colon (:) to separate items in the path. for Windows, use a semicolon (;) to separate items.--enable-previewβ allows code to depend on the preview features of this release.--execution specificationβ specifies an alternate execution engine, where specification is anExecutionControlspec. see the documentation of the packagejdk.jshell.spifor the syntax of the spec.--feedback modeβ sets the initial level of feedback provided in response to what's entered. the initial level can be overridden within a session by using the/set feedback modecommand. the default isnormal.
the following values are valid for mode:
verboseβ provides detailed feedback for entries. additional information about the action performed is displayed after the result of the action. the next prompt is separated from the feedback by a blank line.normalβ provides an average amount of feedback. the next prompt is separated from the feedback by a blank line.conciseβ provides minimal feedback. the next prompt immediately follows the code snippet or feedback.silentβ provides no feedback. the next prompt immediately follows the code snippet.customβ provides custom feedback based on how the mode is defined. custom feedback modes are created within JShell by using the/set modecommand.
--help,-h,-?β prints a summary of standard options and exits the tool.--help-extra,-Xβ prints a summary of nonstandard options and exits the tool. nonstandard options are subject to change without notice.-Jflagβ passes flag to the runtime system, but has no effect on the execution of code snippets. to specify flags that affect the execution of code snippets, use-Rflag. alternatively, use-Jflagwith--execution local.--module-path modulepathβ specifies where to find application modules. for Linux and macOS, use a colon (:) to separate items in the path. for Windows, use a semicolon (;) to separate items.--no-startupβ prevents startup scripts from running when JShell starts. use this option to run only the scripts entered on the command line when JShell is started, or to start JShell without any preloaded information if no scripts are entered. > this option can't be used if the--startupoption is used.-qβ sets the feedback mode toconcise, which is the same as entering--feedback concise.-Rflagβ passes flag to the runtime system only when code snippets are executed. for example,-R-Dfoo=barmeans that execution of the snippetSystem.getProperty("foo")will return"bar".-sβ sets the feedback mode tosilent, which is the same as entering--feedback silent.--show-versionβ prints version information and enters the tool.--startup fileβ overrides the default startup script for this session. the script can contain any valid code snippets or commands.
the script can be a local file or one of the following predefined scripts:
DEFAULTβ loads the default entries, which are commonly used as imports.JAVASEβ imports all Java SE packages.PRINTINGβ definesprint,println, andprintfas jshell methods for use within the tool.TOOLINGβ definesjavac,jar, and other methods for running JDK tools via their command-line interface within the jshell tool.
for more than one script, provide a separate instance of this option for each script. startup scripts are run when JShell is first started and when the session is restarted with the /reset, /reload, or /env command. startup scripts are run in the order in which they're entered on the command line.
this option can't be used if the --no-startup option is used.
-vβ sets the feedback mode toverbose, which is the same as entering--feedback verbose.--versionβ prints version information and exits the tool.
π JSHELL COMMANDS π
within the jshell tool, commands are used to modify the environment and manage code snippets. this is where the main character energy really kicks in π
π /drop
/drop {name|id|startID-endID} [{name|id|startID-endID}...]
drops snippets identified by name, ID, or ID range, making them inactive. for a range of IDs, provide the starting ID and ending ID separated with a hyphen. to provide a list, separate the items in the list with a space. use the /list command to see the IDs of code snippets.
π /edit
/edit [option]
opens an editor. if no option is entered, then the editor opens with the active snippets.
the following options are valid:
{name|id|startID-endID} [{name|id|startID-endID}...]β opens the editor with the snippets identified by name, ID, or ID range. for a range of IDs, provide the starting ID and ending ID separated with a hyphen. to provide a list, separate the items in the list with a space. use the/listcommand to see the IDs of code snippets.-allβ opens the editor with all snippets, including startup snippets and snippets that failed, were overwritten, or were dropped.-startβ opens the editor with startup snippets that were evaluated when JShell was started.
to exit edit mode, close the editor window, or respond to the prompt provided if the -wait option was used when the editor was set.
use the /set editor command to specify the editor to use. if no editor is set, then the following environment variables are checked in order: JSHELLEDITOR, VISUAL, and EDITOR. if no editor is set in JShell and none of the editor environment variables is set, then a simple default editor is used π§
π /env
/env [options]
displays the environment settings, or updates the environment settings and restarts the session. if no option is entered, then the current environment settings are displayed. if one or more options are entered, then the session is restarted as follows:
- updates the environment settings with the provided options.
- resets the execution state.
- runs the startup scripts.
- silently replays the history in the order entered. the history includes all valid snippets or
/dropcommands entered at thejshellprompt, in scripts entered on the command line, or scripts entered with the/opencommand.
environment settings entered on the command line or provided with a previous /reset, /env, or /reload command are maintained unless an option is entered that overwrites the setting π
The following options are valid, bestie β this is the little crew of flags that shows up here:
--add-modules module[,module...]β tells it which root modules to resolve on top of the initial module β¨--add-exports source-module/package=target-module[,target-module]*β exportspackagefrom source-module over to target-module, and you can list a whole squad of target modules separated by commas π--class-path pathβ where it goes hunting for class files, aka the directories and archives it searches. Heads up though: this option overrides the path that's chilling in theCLASSPATHenvironment variable. If that env var isn't set and you didn't pass this option, then it just searches the current directory, no big deal. On Linux and macOS you separate the items in the path with a colon (:), and on Windows you use a semicolon (;) π«Ά--module-path modulepathβ tells it where to find your application modules. Same separator rules, periodt: colon (:) on Linux and macOS, semicolon (;) on Windows πΈ
π /exit [integer-expression-snippet]
Exits the tool. That's it, that's the vibe.
If you don't feed it a snippet, the exit status is literally zero. If you do enter a snippet and the result of that snippet is an integer, then that result gets used as the exit status β main character energy fr fr.
But if an error occurs, or the snippet's result isn't an integer? An error is displayed and the tool stays active. No escape. You live here now π
π /history
Displays what was entered in this session. Basically the receipts of everything you typed, bestie.
β¨ /help [command|subject]
Displays information about commands and subjects. If you enter no options at all, you get a summary of info for all the commands plus a list of the available subjects. If you give it a valid command, you get the expanded info for that command. And if you enter a valid subject, you get the info about that subject.
The following values for subject are valid, iykyk:
contextβ describes the options that are available for configuring the environmentintroβ provides an introduction to the tool (hi, welcome, here's the lore)shortcutsβ describes the keystrokes for completing commands and snippets. See Input Shortcuts π
π¦ /imports
Displays the current active imports β and yes, that includes the ones from the startup scripts and the scripts you entered on the command line when JShell was started. Full transparency, we love to see it.
πΈ /list [option]
Displays a list of snippets and their IDs. If you enter no option, you get all the active snippets displayed β but the startup snippets stay hidden, they're shy π
The following options are valid:
{name|id|startID-endID} [{name|id|startID-endID}...]β displays the snippets identified by name, ID, or ID range. For a range of IDs, hand over the starting ID and the ending ID separated with a hyphen. Making a list? Separate the items with a space, bestie.-allβ displays all snippets, including startup snippets and the ones that failed, got overwritten, or were dropped. Little ID decoder for you: IDs that begin withsare startup snippets, and IDs that begin witheare snippets that failed π-startβ displays the startup snippets that were evaluated when JShell was started
π /methods [option]
Displays info about the methods that were entered. No option? Then you get the name, parameter types, and return type of all the active methods. Gorgeous, complete, iconic.
The following options are valid:
{name|id|startID-endID} [{name|id|startID-endID}...]β displays info for the methods identified by name, ID, or ID range. For a range of IDs, give the starting ID and ending ID separated with a hyphen. For a list, separate the items in the list with a space. Pro tip from me to you: use the/listcommand to see the IDs of the code snippets π«Ά-allβ displays info for all methods, including the ones added when JShell was started, plus methods that failed, were overwritten, or were dropped-startβ displays info for the startup methods that were added when JShell was started
π /open file
Opens the script you specified and reads the snippets into the tool. That script can be a local file, or it can be one of these predefined scripts β yes, they're built in, no cap:
DEFAULTβ loads the default entries, which are commonly used as importsJAVASEβ imports all Java SE packagesPRINTINGβ definesprint,println, andprintfas jshell methods for use within the toolTOOLINGβ definesjavac,jar, and other methods for running JDK tools via their command-line interface, right there inside the jshell tool π₯
β /reload [options]
Restarts the session, and here's exactly how it does it:
- Updates the environment settings with the options you gave it, if any
- Resets the execution state
- Runs the startup scripts
- Replays the history in the order entered β and that history includes all valid snippets or
/dropcommands entered at thejshellprompt, in scripts entered on the command line, or in scripts entered with the/opencommand
Environment settings you entered on the command line, or that you provided with a previous /reset, /env, or /reload command, are maintained β unless you enter an option that overwrites the setting. Rude but fair.
The following options are valid:
--add-modules module[,module...]β specifies the root modules to resolve in addition to the initial module--add-exports source-module/package=target-module[,target-module]*β adds an export ofpackagefrom source-module to target-module--class-path pathβ specifies the directories and archives that are searched to locate class files. This option overrides the path in theCLASSPATHenvironment variable. If the environment variable isn't set and this option isn't used, then the current directory is searched. For Linux and macOS, use a colon (:) to separate items in the path. For Windows, use a semicolon (;) to separate items.--module-path modulepathβ specifies where to find application modules. For Linux and macOS, use a colon (:) to separate items in the path. For Windows, use a semicolon (;) to separate items.-quietβ replays the valid history without displaying it. Errors are still displayed though, we're not hiding those π-restoreβ resets the environment to the state at the start of the previous run of the tool, or to the last time a/reset,/reload, or/envcommand was executed in the previous run. The valid history since that point is replayed. Use this option to restore a previous JShell session β genuinely such a slay feature π
π§ /reset [options]
Discards all entered snippets and restarts the session like this:
- Updates the environment settings with the provided options, if any
- Resets the execution state
- Runs the startup scripts
History is not replayed. All code that was entered is lost. Gone. Poof. Say goodbye π
Environment settings entered on the command line or provided with a previous /reset, /env, or /reload command are maintained unless an option is entered that overwrites the setting.
The following options are valid:
--add-modules module[,module...]β specifies the root modules to resolve in addition to the initial module--add-exports source-module/package=target-module[,target-module]*β adds an export ofpackagefrom source-module to target-module--class-path pathβ specifies the directories and archives that are searched to locate class files. This option overrides the path in theCLASSPATHenvironment variable. If the environment variable isn't set and this option isn't used, then the current directory is searched. For Linux and macOS, use a colon (:) to separate items in the path. For Windows, use a semicolon (;) to separate items.--module-path modulepathβ specifies where to find application modules. For Linux and macOS, use a colon (:) to separate items in the path. For Windows, use a semicolon (;) to separate items.
π /save [options] file
Saves snippets and commands to the file you specified. If you enter no options, then the active snippets are what get saved. Simple, clean, hygienic.
The following options are valid:
{name|id|startID-endID} [{name|id|startID-endID}...]β saves the snippets and commands identified by name, ID, or ID range. For a range of IDs, provide the starting ID and ending ID separated with a hyphen. To provide a list, separate the items in the list with a space. Again: use the/listcommand to see the IDs of the code snippets π-allβ saves all snippets, including startup snippets and snippets that were overwritten or failed-historyβ saves the sequential history of all commands and snippets entered in the current session-startβ saves the current startup settings. If no startup scripts were provided, then an empty file is saved (yes, an empty file β that's the correct behaviour, don't @ me)
π /set [setting]
Sets configuration information β including the external editor, startup settings, and feedback mode. This command is also the one you use to create a custom feedback mode with customized prompt, format, and truncation values. And if you enter no setting at all, then the current setting for the editor, startup settings, and feedback mode are displayed for you.
The following values are valid for setting:
editor [options] [command]
okay so this one sets the command that launches your external editor when you type /edit π
the command can totally include arguments, just separate them with spaces. type it with no command and no options and it'll show you what the current setting is.
the options that actually work here:
-defaultβ sets your editor to the default editor that ships with JShell β¨ but heads up: you can't use this one if you're also entering a command to start an editor.-deleteβ sets the editor back to whatever was in effect when the session started π«Ά if you pair it with-retain, then the retained editor setting gets deleted and the editor gets set to the first one of these environment variables it finds:JSHELLEDITOR,VISUAL, orEDITOR. and if none of those editor environment variables are set? then this option just sets the editor to the default editor. also, same deal as above: can't use it if a command for starting an editor is entered.-retainβ saves your editor setting across sessions πΎ if you enter no other option and no command, then the current setting is what gets saved.-waitβ prompts you to say when editing is done π otherwise control goes back to JShell the moment the editor exits. use this one if your editor exits immediately, like when an edit window already exists. and this option is only valid when a command for starting an editor is entered.
feedback [mode]
sets the feedback mode that JShell uses to respond to your input π type it with no mode and it'll show you the current one.
the valid modes are: concise, normal, silent, verbose, plus any custom mode you made with the /set mode command β¨
format mode field "format-string" selector
sets the format of the feedback JShell gives you back πΈ and the display logic here is kinda layered so stay with me:
- no mode entered β current formats for all fields for all feedback modes get displayed
- only a mode entered β current formats for that mode get displayed
- only a mode and field entered β current formats for that field get displayed
to actually define a format, you need these arguments:
modeβ the feedback mode the response format applies to. only custom modes created with the/set modecommand can be modified πfieldβ the context-specific field the response format applies to. the fields are described in the online help, which you get to from JShell using/help /set formatπ"format-string"β the string used as the response format for the specified field and selector. the structure of the format string is, again, described in the online help via/help /set formatβ¨selectorβ the context in which the response format applies. selectors are described in the online help too, same route:/help /set formatπ¦
mode [mode-name] [existing-mode] [options]
creates a custom feedback mode with the name you give it π if you enter no mode name, you get the settings for all modes displayed, which includes the mode, prompt, format, and truncation settings. and if you hand it the name of an existing mode, the settings from that existing mode get copied over to the new one you're creating. cute, right? π
the valid options:
-command|-quietβ sets the level of feedback shown for commands when using this mode. this option is required when creating a feedback mode.-commandshows info and verification feedback for commands;-quietshows only the essential stuff, like error messages π-deleteβ deletes the named feedback mode for this session. the name of the mode to delete is required. to permanently delete a retained mode, pair this with the-retainoption. and nope, predefined modes can't be deleted π-retainβ saves the named feedback mode across sessions. name of the mode to retain is required πΎ
then you configure your shiny new feedback mode with the /set prompt, /set format, and /set truncation commands β¨
and to actually start using it, hit up /set feedback π
prompt mode "prompt-string" "continuation-prompt-string"
sets the prompts for input inside JShell π no mode entered β current prompts for all feedback modes displayed. only a mode entered β current prompts for that mode displayed.
to define a prompt, these arguments are required:
modeβ the feedback mode the prompts apply to. only custom modes created with the/set modecommand can be modified π"prompt-string"β the string used as the prompt for the first line of input."continuation-prompt-string"β the string used as the prompt for the additional input lines you need to complete a snippet π¦
start [-retain] [file [file...]|option]
sets the names of the startup scripts used the next time you enter /reset, /reload, or /env π₯ enter more than one script and they run in the order you entered them. enter no scripts and no options and you'll see the current startup settings.
the scripts can be local files, or one of these predefined ones:
DEFAULTβ loads the default entries, which are commonly used as imports β¨JAVASEβ imports all Java SE packages πPRINTINGβ definesprint,println, andprintfas jshell methods for use within the tool π¨οΈTOOLINGβ definesjavac,jar, and other methods for running JDK tools via their command-line interface inside the jshell tool π οΈ
the valid options:
-defaultβ sets the startup settings to the default settings.-noneβ specifies that no startup settings are used π
and use the -retain option to save the start setting across sessions πΎ
truncation mode length selector
sets the maximum length of a displayed value βοΈ no mode entered β current truncation values for all feedback modes displayed. only a mode entered β current truncation values for that mode displayed.
to define truncation values, these arguments are required:
modeβ the feedback mode the truncation value applies to. only custom modes created with the/set modecommand can be modified πlengthβ the unsigned integer to use as the maximum length for the specified selector π’selectorβ the context the truncation value applies to. selectors are described in the online help, which you reach from JShell using/help /set truncationπ
/types [option]
displays the classes, interfaces, and enums you entered π¦ no option entered β all current active classes, interfaces, and enums get displayed.
the valid options:
{name|id|startID-endID} [{name|id|startID-endID}...]β displays info for classes, interfaces, and enums identified by name, ID, or ID range. for a range of IDs, give the starting ID and ending ID separated by a hyphen. for a list, separate the items with a space. and use the/listcommand to see the IDs of the code snippets β¨-allβ displays info for all classes, interfaces, and enums, including the ones added when JShell was started, plus ones that failed, were overwritten, or were dropped π-startβ displays info for startup classes, interfaces, and enums that were added when JShell was started π
/vars [option]
displays the name, type, and value of the variables you entered π no option entered β all current active variables get displayed.
the valid options:
{name|id|startID-endID} [{name|id|startID-endID}...]β displays info for variables identified by name, ID, or ID range. for a range of IDs, give the starting ID and ending ID separated by a hyphen. for a list, separate the items with a space. and use/listif you need to see the IDs of the code snippets π-allβ Displays information for all variables, including those added when JShell was started, and variables that failed, were overwritten, or were dropped. Itβs the full lore, bestie π-startβ Displays information for startup variables that were added when JShell was started. The origin-story variables β¨/?β Same as the/helpcommand. Literally the shortcut π«Ά/!β Reruns the last snippet. Yes, the last one π₯/{name|id|startID-endID} [{name|id|startID-endID}...]β Reruns the snippets identified by ID, range of IDs, or name. For a range of IDs, provide the starting ID and ending ID separated with a hyphen. To provide a list, separate the items in the list with a space. The first item in the list must be an ID or ID range. Use the/listcommand to see the IDs of the code snippets. The syntax is giving βpick your favesβ energy π/-nβ Reruns the -nth previous snippet. For example, if 15 code snippets were entered, then/-4runs the 11th snippet. Commands aren't included in the count. Math but make it shell π
β¨ INPUT SHORTCUTS β¨
The following shortcuts are available for entering commands and snippets in JShell. These are your little cheat codes, no cap π
π§ Tab completion
<tab>β When entering snippets, commands, subcommands, command arguments, or command options, use the Tab key to automatically complete the item. If the item can't be determined from what was entered, then possible options are provided. Autocomplete said βI got youβ β¨<tab>in a method call β When entering a method call, use the Tab key after the method call's opening parenthesis to see the parameters for the method. If the method has more than one signature, then all signatures are displayed. Pressing the Tab key a second time displays the description of the method and the parameters for the first signature. Continue pressing the Tab key for a description of any additional signatures. Method intel unlocked π¦Shift+<Tab> Vβ After entering a complete expression, use this key sequence to convert the expression to a variable declaration of a type determined by the type of the expression. Variable glow-up πShift+<Tab> Mβ After entering a complete expression or statement, use this key sequence to convert the expression or statement to a method declaration. If an expression is entered, the return type is based on the type of the expression. Methodify it πΈShift+<Tab> Iβ When an identifier is entered that can't be resolved, use this key sequence to show possible imports that resolve the identifier based on the content of the specified class path. Import rescue mission π«Ά
π Command abbreviations
An abbreviation of a command is accepted if the abbreviation uniquely identifies a command. For example, /l is recognized as the /list command. However, /s isn't a valid abbreviation because it can't be determined if the /set or /save command is meant. Use /se for the /set command or /sa for the /save command. iykyk π
Abbreviations are also accepted for subcommands, command arguments, and command options. For example, use /m -a to display all methods. Slay π
π°οΈ History navigation
A history of what was entered is maintained across sessions. Use the up and down arrows to scroll through commands and snippets from the current and past sessions. Use the Ctrl key with the up and down arrows to skip all but the first line of multiline snippets. Time travel but make it shell β¨
π History search
Use the Ctrl+R key combination to search the history for the string entered. The prompt changes to show the string and the match. Ctrl+R searches backwards from the current location in the history through earlier entries. Ctrl+S searches forward from the current location in the history through later entries. The search bar said βIβm built inβ π₯
π INPUT EDITING π
The editing capabilities of JShell are similar to that of other common shells. Keyboard keys and key combinations provide line editing shortcuts. The Ctrl key and Meta key are used in key combinations. If your keyboard doesn't have a Meta key, then the Alt key is often mapped to provide Meta key functionality.
Quick vibe check: no Meta key? Your Alt key is often doing the Meta keyβs job, bestie π«Ά
β Line Editing Shortcuts β
Returnβ Enter the current line.Left arrowβ Move the cursor to the left one character.Right arrowβ Move the cursor to the right one character.Ctrl+Aβ Move the cursor to the beginning of the line.Ctrl+Eβ Move the cursor to the end of the line.Meta+Bβ Move the cursor to the left one word.Meta+Fβ Move the cursor to the right one word.Deleteβ Delete the character under the cursor.Backspaceβ Delete the character before the cursor.Ctrl+Kβ Delete the text from the cursor to the end of the line.Meta+Dβ Delete the text from the cursor to the end of the word.Ctrl+Wβ Delete the text from the cursor to the previous white space.Ctrl+Yβ Paste the most recently deleted text into the line.Meta+Yβ AfterCtrl+Y, press to cycle through the previously deleted text.
π EXAMPLE OF STARTING AND STOPPING A JSHELL SESSION π
JShell is provided with the JDK. To start a session, enter jshell on the command line. A welcome message is printed, and a prompt for entering commands and snippets is provided.
% jshell
| Welcome to JShell -- Version 9
| For an introduction type: /help intro
jshell>
To see which snippets were automatically loaded when JShell started, use the /list -start command. The default startup snippets are import statements for common packages. The ID for each snippet begins with the letter s, which indicates it's a startup snippet.
jshell> /list -start
s1 : import java.io.*;
s2 : import java.math.*;
s3 : import java.net.*;
s4 : import java.nio.file.*;
s5 : import java.util.*;
s6 : import java.util.concurrent.*;
s7 : import java.util.function.*;
s8 : import java.util.prefs.*;
s9 : import java.util.regex.*;
s10 : import java.util.stream.*;
jshell>
To end the session, use the /exit command.
jshell> /exit
| Goodbye
%
πΈ EXAMPLE OF ENTERING SNIPPETS πΈ
Snippets are Java statements, variable definitions, method definitions, class definitions, import statements, and expressions. Terminating semicolons are automatically added to the end of a completed snippet if they're missing.
The following example shows two variables and a method being defined, and the method being run. Note that a scratch variable is automatically created to hold the result because no variable was provided.
jshell> int a=4
a ==> 4
jshell> int b=8
b ==> 8
jshell> int square(int i1) {
...> return i1 * i1;
...> }
| created method square(int)
jshell> square(b)
$5 ==> 64
π EXAMPLE OF CHANGING SNIPPETS π
Change the definition of a variable, method, or class by entering it again.
The following examples shows a method being defined and the method run:
jshell> String grade(int testScore) {
...> if (testScore >= 90) {
...> return "Pass";
...> }
...> return "Fail";
...> }
| created method grade(int)
jshell> grade(88)
$3 ==> "Fail"
To change the method grade to allow more students to pass, enter the method definition again and change the pass score to 80. Use the up arrow key to retrieve the previous entries to avoid having to reenter them and make the change in the if statement. The following example shows the new definition and reruns the method to show the new result:
jshell> String grade(int testScore) {
...> if (testScore >= 80) {
...> return "Pass";
...> }
...> return "Fail";
...> }
| modified method grade(int)
jshell> grade(88)
$5 ==> "Pass"
For snippets that are more than a few lines long, or to make more than a few changes, use the /edit command to open the snippet in an editor. After the changes are complete, close the edit window to return control to the JShell session. The following example shows the command and the feedback provided when the edit window is closed. The /list command is used to show that the pass score was changed to 85.
jshell> /edit grade
| modified method grade(int)
jshell> /list grade
6 : String grade(int testScore) {
if (testScore >= 85) {
return "Pass";
}
return "Fail";
}
π EXAMPLE OF CREATING A CUSTOM FEEDBACK MODE π
Okay so real talk β the feedback mode is basically the whole personality of your shell. It controls three things, bestie:
- the prompt that's displayed
- the feedback messages that are provided as snippets are entered
- the maximum length of a displayed value
Predefined feedback modes are provided (thank u, defaults π), and commands for creating custom feedback modes are also provided. So yeah β you can build your own. Let's go.
β¨ Step one: make the mode β¨
Use the /set mode command to create a new feedback mode. In the following example, the new mode mymode is based on the predefined feedback mode normal, and verifying command feedback is displayed:
jshell> /set mode mymode normal -command
| Created new feedback mode: mymode
Lowkey iconic β it's born, it's slaying, it exists.
πΈ Step two: the prompts πΈ
Because the new mode is based on the normal mode, the prompts are the same. The following example shows how to see what prompts are used and then changes the prompts to custom strings. The first string represents the standard JShell prompt. The second string represents the prompt for additional lines in multiline snippets.
First, peek at what you got:
jshell> /set prompt mymode
| /set prompt mymode "\njshell> " " ...> "
Then make it yours:
jshell> /set prompt mymode "\nprompt$ " " continue$ "
The way that second one is for your continuation linesβ¦ chef's kiss ππ
π¦ Step three: truncation nation π¦
The maximum length of a displayed value is controlled by the truncation setting. Different types of values can have different lengths. The following example sets an overall truncation value of 72, and a truncation value of 500 for variable value expressions:
jshell> /set truncation mymode 72
jshell> /set truncation mymode 500 varvalue
So 72 for the general vibe, 500 specifically for varvalue because she's extra. Periodt.
β Step four: format the feedback β
The feedback displayed after snippets are entered is controlled by the format setting and is based on the type of snippet entered and the action taken for that snippet. In the predefined mode normal, the string created is displayed when a method is created. The following example shows how to change that string to defined:
jshell> /set format mymode action "defined" added-primary
Not me customizing one specific string because I can πβ¨
π Step five: actually use it π
Use the /set feedback command to start using the feedback mode that was just created. The following example shows the custom mode in use:
jshell> /set feedback mymode
| Feedback mode: mymode
prompt$ int square (int num1){
continue$ return num1*num1;
continue$ }
| defined method square(int)
prompt$
Look at those custom prompts doing their little walk ππ prompt$ and continue$ out here with main character energy, and the method feedback saying defined because we told it to. Slay.
Heads up bestie: this is a reference doc, so all those flags and strings are doing exactly what the page says β nothing more, nothing less. No cap.
And that's the whole page! π This one came from the JDK 23 docs, dated 2024 β so if you're reading this, thank the 2024-era JDK crew for writing it all down. Go forth and customize your prompts, you beautiful nerd π«Άππ
π¦ where this page comes from
- opensuse-leap 16.0: java-23-openjdk-devel 23.0.2.0-160000.1.1 Β· Apache-1.1 AND Apache-2.0 AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-only WITH Classpath-exception-2.0 AND LGPL-2.0-only AND MPL-1.0 AND MPL-1.1 AND SUSE-Public-Domain AND W3C
- opensuse-leap 16.0: java-23-openjdk-devel 23.0.2.0-160000.1.1 Β· Apache-1.1 AND Apache-2.0 AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-only WITH Classpath-exception-2.0 AND LGPL-2.0-only AND MPL-1.0 AND MPL-1.1 AND SUSE-Public-Domain AND W3C
- opensuse-leap 16.0: java-23-openjdk-devel 23.0.2.0-160000.1.1 Β· Apache-1.1 AND Apache-2.0 AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-only WITH Classpath-exception-2.0 AND LGPL-2.0-only AND MPL-1.0 AND MPL-1.1 AND SUSE-Public-Domain AND W3C
- opensuse-leap 16.0: java-23-openjdk-devel 23.0.2.0-160000.1.1 Β· Apache-1.1 AND Apache-2.0 AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-only WITH Classpath-exception-2.0 AND LGPL-2.0-only AND MPL-1.0 AND MPL-1.1 AND SUSE-Public-Domain AND W3C
- Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms