7 Scripts

A JShell script is a sequence of snippets and JShell commands in a file, one snippet or command per line.

Scripts can be a local file, or one of the following predefined scripts:

Script Name Script Contents

DEFAULT

Includes commonly needed import declarations. This script is used if no other startup script is provided.

JAVASE

Imports the core Java SE API defined by the java.se module, which causes a noticeable delay in starting JShell due to the number of packages.

PRINTING

Defines JShell methods that redirect to the print, println, and printf methods in PrintStream.

TOOLING

Defines JShell methods accessing JDK tools like javac, javadoc, and javap using their command-line interface.

Startup Scripts

Startup scripts contain snippets and commands that are loaded when a JShell session is started. The default startup script contains common import statements. You can create custom scripts as needed.

Startup scripts are loaded each time the jshell tool is reset. Reset occurs during the initial startup and with the /reset, /reload, and /env commands. If you do not set the script, then, the default startup script, DEFAULT, is used. This default script defines commonly needed import declarations.

Note:

The Java language defines that the java.lang package is automatically imported so this package doesn’t need to be explicitly imported.

To set the startup script, use the /set start command:

jshell> /set start mystartup.jsh

jshell> /reset
|  Resetting state.

As with all /set commands, the duration of the setting is the current session unless the -retain option is used. Typically, the -retain option isn’t used when you test a startup script setting. When the desired setting is found, use the-retain option to preserve it:

jshell> /set start -retain

The startup script is then loaded the next time you start the jshell tool.

Remember that the startup scripts are loaded into the current session only when the state is reset. The contents of the script is stored, not a reference to the script. The script is read only at the time the /set start command is run. However, predefined scripts are loaded by reference and can be updated with new releases of the JDK.

Startup scripts can also be specified with the --startup command-line flag:

% jshell --startup mystartup.jsh

For experimentation, it is useful to have print methods that don't need the System.out. prefix. Use the predefined PRINTING script to access the print, println, and printf methods. You can specify more than one startup script with /set start. The following example sets the startup to load both the default imports and printing definitions:

jshell> /set start -retain DEFAULT PRINTING

jshell> /exit
|  Goodbye

% jshell
|  Welcome to JShell -- Version 9
|  For an introduction type: /help intro

jshell> println("Hello World!")
Hello World!

The -retain flag is used to set these predefined scripts as the startup scripts for future sessions of the jshell tool. Use /set start without arguments to see the details of what is defined by these startup scripts.

To set more than one startup script on the command line, use the --startup flag for each script:

% jshell --startup DEFAULT --startup PRINTING

Creating and Loading Scripts

Use scripts to set up your JShell session with import statements and code that you want available during the session.

Creating Scripts

A script can be created externally in an editor, or generated from items entered in JShell. Use one of the following commands to create a script from the entries in a JShell session:

jshell> /save mysnippets.jsh

jshell> /save -history myhistory.jsh

jshell> /save -start mystartup.jsh

The first command shown in the example saves the current active snippets to mysnippets.jsh. The second command shown saves the history of all of the snippets and commands, both valid and invalid, to myhistory.jsh. The last command shown saves the contents of the current startup script setting to mystartup.jsh. The file name provided can be any valid file path and name.

Loading Scripts

Scripts can be loaded from the command line when a JShell session is started:

% jshell mysnippets.jsh

Scripts can also be loaded within a JShell session by using the /open command:

jshell> /open PRINTING

Accessing Command Line Tools Through JShell

The predefinded script TOOLING provides direct access to the JDK's command line tools, such as javac, javadoc, and javap, within the jshell tool. Load the TOOLING script when the jshell tool starts by running the following command:

jshell TOOLING

Alternatively, load it within within a JShell session with the following command:

jshell> /open TOOLING

Once you have loaded the TOOLING script, you can run observable tool services that have implemented the java.util.spi.ToolProvider interface by passing a name and an array of arguments to the run(String, String...) method. Call tools() to print a sorted list of names for all runnable tools. For example:

jshell> /open TOOLING

jshell> tools()
jar
javac
javadoc
javap
jdeps
jlink
jmod
jpackage

jshell> run("javac","--version")
javac 22

For well known JDK tools, the TOOLING script defines convenience methods such as javac(String... args) { run("javac", args); }. This shortens the last call of the previous example to the following:


jshell> javac("--version")
javac 22

In addition, the TOOLING script defines a javap method that takes a class literal. With this method, you can disassemble and print an overview of an existing or newly created type without leaving the JShell session. For example:

jshell> interface Empty {}
|  created interface Empty

jshell> javap(Empty.class)
Classfile /C:/tmp/TOOLING-13600306095244067647.class
  Last modified Oct 4, 2023; size 191 bytes
  SHA-256 checksum 1e53e9d7d4549a00361937701d3b0a613b520a68854310796db7879efc08d195
  Compiled from "$JShell$22.java"
public interface REPL.$JShell$22$Empty
  minor version: 0
  major version: 65
  flags: (0x0601) ACC_PUBLIC, ACC_INTERFACE, ACC_ABSTRACT
  this_class: #1                          // REPL/$JShell$22$Empty
  super_class: #3                         // java/lang/Object
  interfaces: 0, fields: 0, methods: 0, attributes: 3
Constant pool:
   #1 = Class              #2             // REPL/$JShell$22$Empty
   #2 = Utf8               REPL/$JShell$22$Empty
   #3 = Class              #4             // java/lang/Object
   #4 = Utf8               java/lang/Object
   #5 = Utf8               SourceFile
   #6 = Utf8               $JShell$22.java
   #7 = Utf8               NestHost
   #8 = Class              #9             // REPL/$JShell$22
   #9 = Utf8               REPL/$JShell$22
  #10 = Utf8               InnerClasses
  #11 = Utf8               Empty
{
}
SourceFile: "$JShell$22.java"
NestHost: class REPL/$JShell$22
InnerClasses:
  public static #11= #1 of #8;            // Empty=class REPL/$JShell$22$Empty of class REPL/$JShell$22

The following JShell script creates a module named com.greetings that prints Greetings!. It creates a modular JAR that contains the module com.greetings, then prints its module declaration. Afterwards, the script creates a runtime image with the jlink tool that contains the module com.greetings.

This example is based on the example described in Project Jigsaw: Module System Quick-Start Guide.

/open PRINTING

print(
    """
    -----------------------------------------------
    Project Jigsaw: Module System Quick-Start Guide
    -----------------------------------------------
    """)

/* Create a module named com.greetings that prints "Greetings!". */

Files.createDirectories(Path.of("src/com.greetings/com/greetings"))

/* Create a module declaration named module-info.java */

Files.writeString(Path.of("src/com.greetings/module-info.java"),
    """
    module com.greetings {}
    """)
    
/* Create the main class */    

Files.writeString(Path.of("src/com.greetings/com/greetings/Main.java"),
    """
    package com.greetings;
    public class Main {
        public static void main(String[] args) {
            System.out.println("Greetings!");
        }
    }
    """)

/open TOOLING

/* Compile the source code to the directory to the directory mods/com.greetings */

javac("-d", "mods", "--module", "com.greetings", "--module-source-path", "src")

/* Create a modular JAR that contains the module greetings.com. */

jar("--create", "--file=mlib/com.greetings.jar", "--main-class=com.greetings.Main", "-C", "mods/com.greetings", ".")

/* Print the module declaration of the modular JAR com.greetings */

jar("--describe-module", "--file=mlib/com.greetings.jar")

/* Create a runtime image in the folder greetingsruntime that contains the module com.greetings. /* 

jlink("--module-path", "mlib", "--add-modules", "com.greetings", "--output", "greetingsruntime", "--launcher", "greet=com.greetings")

/* You can run com.greetings.Main with this runtime as follows:
 *
 * greetingsruntime/bin/java --module com.greetings
 */
 
/exit