Sub topic 13
Running, Saving and Loading Scripts
This chapter assumes a JDK 9 or later, the jshell command on your PATH, basic Java syntax, and comfort using a terminal. A JShell script is a text file containing Java snippets and JShell commands. JShell reads the file from top to bottom, just as if you entered each line in an interactive session.
Creating and running a script
Create a file named demo.jsh with these contents:
int x = 10;
int doubled = x * 2;
System.out.println(doubled);
/exitRun it from the directory containing the file:
jshell demo.jshThe session creates x, creates doubled, prints 20, and then exits because /exit is the final command. Without /exit, JShell normally remains open after it finishes reading the file, so you can inspect the results interactively.
A script can contain declarations, expressions, statements, imports, and slash commands. Each complete unit is a snippet. The script's snippets run in order, so a later snippet can use a variable declared earlier.
Loading a script into an existing session
Start JShell normally:
jshellThen load a file with /open:
jshell> /open demo.jsh
20/open adds the file's snippets to the current session. Existing variables and methods remain available, and the loaded snippets can use them. This makes small files useful for repeatable setup, such as defining test data or helper methods.
The following commands have different purposes:
| Command | Purpose |
|---|---|
| `jshell file.jsh` | Start JShell and process a script |
| `/open file.jsh` | Load a script into the current session |
| `/save file.jsh` | Save session snippets to a file |
Saving the current session
While working interactively, save your snippets with:
jshell> /save session.jshYou can open the saved file later or inspect it with a text editor. Saving is useful when an experiment becomes a reusable example. Review the file before sharing it. It may contain exploratory snippets, repeated declarations, or commands that you do not want to run again.
Use /help /save and /help /open to check options supported by your installed JDK. JShell versions can differ in available commands and feedback text.
Exercise
What happens if a script declares int total = 3;, then evaluates total + 2, and contains no /exit command?
Show answer
JShell processes both snippets, reports the result 5, and then remains open for interactive input.