Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 201 ยท Getting Started

JShell: the Java REPL

Learn JShell, Java's built-in REPL. Type expressions, declare variables and methods, use commands like /vars and /list, and drive JShell from your own code.

Normally a Java experiment needs a file, a class, a main method, a compile step and a run step. That is a lot of ceremony to answer a question like "what does "a,b,,".split(",") return?" JShell removes the ceremony. It is a REPL (read-eval-print loop) that ships with every JDK since Java 9: you type a piece of Java, it runs immediately, and it prints the result.

JShell is perfect for learning the language, trying a library method before you put it in a program, and checking a quick calculation. In this lesson you'll learn how a session works, the commands that start with a slash, and how to script it. Because our in-browser editor can't give you a terminal, the sessions below are shown as read-only transcripts, and the runnable examples use the jdk.jshell API, the same engine, driven from Java code. If you haven't installed a JDK yet, see How Java Works first.

Starting and leaving JShell

Open a terminal and type jshell. You get a prompt, and you can type Java right away:

TEXT
$ jshell
|  Welcome to JShell -- Version 25
|  For an introduction type: /help intro

jshell> 6 * 7
$1 ==> 42

jshell> String name = "Ada"
name ==> "Ada"

jshell> name.toUpperCase()
$3 ==> "ADA"

jshell> /exit
|  Goodbye

Three things to notice:

  • No semicolons needed. JShell adds the final ; for you. You can still type it.
  • No class and no main. Statements, expressions, variables, methods and even whole classes can stand alone at the prompt.
  • Every result is stored. 6 * 7 has no name, so JShell invents one, $1. The number is the snippet ID, which is why the next result is $3 (the second snippet was name). You can use $1 in later expressions.

Leave with /exit or Ctrl+D.

What you can type

Anything that is valid at the top level of a JShell session is called a snippet. There are five kinds of snippet:

Kind Example
Expression Math.sqrt(2)
Variable declaration int count = 0
Statement for (int i = 0; i < 3; i++) System.out.println(i)
Method declaration int square(int n) { return n * n; }
Type declaration record Point(int x, int y) {}

Plus import statements. A transcript with a bit of everything:

TEXT
jshell> int square(int n) { return n * n; }
|  created method square(int)

jshell> square(12)
$2 ==> 144

jshell> record Point(int x, int y) {}
|  created record Point

jshell> var p = new Point(3, 4)
p ==> Point[x=3, y=4]

jshell> p.x() + p.y()
$5 ==> 7

jshell> "a,b,,".split(",").length
$6 ==> 2

That last line answers the question from the start of this lesson: trailing empty strings are removed by split, so you get two parts. Finding that out took five seconds.

Redefining things

In a program, declaring the same variable twice is an error. In JShell you can redefine freely: the new snippet replaces the old one.

TEXT
jshell> int limit = 10
limit ==> 10

jshell> int limit = 99
limit ==> 99

jshell> int square(int n) { return n * n * 1; }
|  modified method square(int)

JShell also tolerates forward references. You can declare a method that calls something that doesn't exist yet; it is marked as "created, however, it cannot be invoked until method helper() is declared", and starts working the moment you define helper. That lets you write top-down, like in a source file.

Imports and defaults

At startup JShell silently imports the packages you need most often: java.io, java.math, java.net, java.nio.file, java.util, java.util.concurrent, java.util.function, java.util.prefs, java.util.regex and java.util.stream. That's why List.of(1, 2, 3) works without an import. For anything else, add your own import snippet, for example import java.time.*. Use /imports to see the active list.

Typing a long expression and forgetting the type of the result? Finish the expression, press Shift+Tab and then v. JShell turns it into a variable declaration with the right type filled in. Press Shift+Tab then i after a class name, and JShell offers the matching imports.

Tab completion and documentation

Press Tab after a dot to list members: name. and Tab shows every method of String. Press Tab again for a method's Javadoc, including its overloads. Press Tab after a partial name to complete variables, classes and commands. This is the quickest way to explore an unfamiliar API without leaving the terminal.

Errors don't end the session

An exception in a plain program ends it. In JShell it prints the stack trace and returns you to the prompt, with all your variables intact:

TEXT
jshell> int zero = 0
zero ==> 0

jshell> 10 / zero
|  Exception java.lang.ArithmeticException: / by zero
|        at (#2:1)

jshell> zero
zero ==> 0

The #2:1 tells you the snippet ID and line. A compile error is reported the same way and the snippet is rejected instead of crashing anything.

The slash commands

Lines that start with / are commands for JShell itself, not Java code. These are the ones you'll use daily:

Command What it does
/vars Lists the variables and their current values
/methods Lists the methods you declared
/types Lists the classes, records, enums and interfaces you declared
/imports Lists the active imports
/list Shows your snippets with their IDs (/list -all includes startup and failed ones)
/drop name Removes a variable, method or type (by name or ID)
/edit Opens snippets in an editor (a small built-in one, or your own)
/save file.jsh Saves your session's snippets to a file
/open file.jsh Runs the snippets stored in a file
/reset Forgets everything and starts fresh
/reload Resets and replays your previous snippets
/history Shows what you typed
/set feedback mode Changes how chatty JShell is (concise, normal, silent, verbose)
/help Lists the commands; /help intro is a short guide

A short example of /vars, /list and /drop:

TEXT
jshell> int a = 5
a ==> 5

jshell> int b = a * 2
b ==> 10

jshell> /vars
|    int a = 5
|    int b = 10

jshell> /drop b
|  dropped variable b

jshell> /list

   1 : int a = 5;

You can also re-run an earlier snippet by its number (/1), repeat the last snippet with /!, or the one before it with /-2.

JShell scripts

Everything you /save is plain Java snippets in a text file. Files conventionally end in .jsh. You can start JShell with a script, or with several:

TEXT
$ jshell setup.jsh
$ jshell -s setup.jsh          # -s: silent, no feedback
$ jshell --class-path lib/app.jar
$ jshell --enable-preview
$ jshell -R-Xmx512m            # -R passes an option to the remote VM that runs your code

Putting /exit as the last line of a script makes it run and quit, which is handy for a one-off task. A script can also be a startup file: /set start myimports.jsh makes JShell run that file every time it starts (use -retain to remember the choice).

Because JShell snippets live at the top level, a few Java rules are relaxed: access modifiers such as public and static on top-level members are ignored (with a warning), and there are no package declarations. If you want to turn an experiment into a real program, copy the snippets into a class and add main. The main method lesson shows the shortest form in Java 25.

Driving JShell from Java code

JShell is not only a terminal tool. The engine is a public API in the jdk.jshell module. IDEs use it for their own "scratch" features, and you can use it to embed a Java evaluator in your own tool. You create a JShell object and feed it source text with eval; every call returns a list of SnippetEvents describing what happened.

The first example evaluates a handful of snippets, including a deliberately incomplete one and an exception. It uses the local execution engine (the code runs inside the same JVM), which is simple and works in our sandbox. Declarations need their semicolon here, because the terminal tool's "add a ; for you" help lives in the tool, not in the engine:

Java Evaluating snippets with the JShell API

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Each event has a status. VALID means the snippet compiled and was accepted. REJECTED means it didn't compile, and diagnostics tells you why. x / 0 is VALID because it compiled, but its exception() is set, which is how a runtime failure appears.

The state persists between calls, just like in the terminal. The next example adds an import (the engine, unlike the jshell tool, starts with no default imports), declares a method and a record, redefines the method, and then asks the engine what it knows:

Java Methods, records and redefinition

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice that redefining square does not produce a rejection: the old snippet becomes OVERWRITTEN, and the call afterwards uses the new body. The engine also reports every snippet that depends on the changed one, so a tool built on this API can show "these three things were recompiled".

When JShell is the right tool

Use JShell when you want a fast answer to a small question: how a method behaves on odd input, what a regular expression matches, how BigDecimal rounds, what an unfamiliar class offers. Many Java developers keep a terminal with jshell open all day, in the same way Python developers keep python.

Don't use it for anything you need to keep. State lives only in the session, and multi-line programs are painful to edit at a prompt. Once an idea grows past a dozen lines, move it to a file and run it with java Main.java, or into a proper project with a build tool. For checking behavior over time, write unit tests instead of repeating manual experiments.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does JShell print for the expression 6 * 7 if you don't assign it to a variable?

    JShell stores the value of an unnamed expression in a scratch variable named $ followed by the snippet ID, so you can use it in later snippets.
  2. 2. You typed int limit = 10 and later int limit = 99 in the same session. What happens?

    JShell lets you redefine variables, methods and types. The new snippet overwrites the old one, and dependent snippets are revalidated.
  3. 3. Which command lists the variables you have declared and their values?

    /vars shows variables with their values. /list shows snippets with IDs, /methods shows declared methods and /history shows what you typed.
  4. 4. What happens when a snippet throws an exception in the jshell tool?

    The exception is reported with the snippet ID and line, and your variables and methods survive, so you can inspect what went wrong.
  5. 5. With the JShell API, what does a SnippetEvent with status REJECTED mean?

    REJECTED means the source was not accepted, for example because of a syntax error or an unknown symbol. A runtime exception shows up as a VALID event with an exception set.

Summary

  • JShell is the JDK's REPL: start it with jshell, type Java without a class or main, and see results immediately.
  • Snippets can be expressions, variables, statements, methods, types and imports. Unnamed results are stored as $1, $2, and so on.
  • Declarations can be redefined, forward references are allowed and an exception never ends the session.
  • Slash commands (/vars, /methods, /list, /drop, /save, /open, /reset, /help) control the tool itself.
  • Tab completion and Shift+Tab help you explore APIs and add imports and variable types.
  • Scripts are plain .jsh files you can run at startup, and the jdk.jshell API lets you embed the same engine in your own programs.

Next: Variables, where you learn how Java stores values, with a JShell session open beside you to try each idea.