Introduction
JShell is the official Read-Eval-Print Loop that shipped with Java 9 in September 2017 under JEP 222. A REPL reads an expression from the user, evaluates it, prints the result, and loops, allowing interactive exploration of a language without the overhead of a project file or a compile cycle. Languages like Python, Ruby, and Scala had enjoyed REPLs for years; Java lagged because the language required every snippet to live inside a class and a method. JShell removed that constraint by accepting snippets, classes, methods, and imports at the prompt without ceremony.
For a Java learner, java 9 jshell repl is the fastest way to test a method, prototype a regular expression, or inspect the contents of a stream. This post shows how to launch JShell, declare variables and methods, evaluate expressions, define classes inline, use the slash commands like /vars and /methods to inspect state, and save and reload sessions for reproducible experimentation.
What is Java 9 JShell REPL?
JShell is a Java language REPL that belongs to the family of interactive language shells, alongside Python's python3, Scala's scala, Kotlin's kotlin, and Groovy's groovysh. Conceptually it is a thin layer over the Java Compiler API and the JDK class loader: every snippet is parsed, compiled in-memory, and loaded into a fresh class, then executed with the result pretty-printed. State is preserved across snippets, so a variable defined in one line is visible in the next.
The most important difference from a normal Java program is that JShell relaxes the rules around top-level statements. You can type "int x = 5;" at the prompt without wrapping it in a class, and JShell records x as a snippet of variable kind. You can also type "int double(int n) { return n * 2; }" at the prompt without a class wrapper, and JShell records double as a method snippet. Errors are reported per snippet, so a broken expression does not invalidate previously defined snippets.
How JShell Works - Step by Step
Step 1: Launch the shell. Run "jshell" from a terminal that has the JDK 9 or later bin on PATH. The prompt appears as "jshell>". The shell automatically imports java.lang, java.io, java.math, java.net, java.util, java.time, java.util.regex, java.util.function, java.util.stream, and a handful of other commonly used packages, so basic snippets work without explicit imports.
Step 2: Declare and use a variable. Type "int x = 10;". JShell prints "x ==> 10". Type "x * 2 + 1". JShell prints the expression result as "$2 ==> 21". The dollar-prefixed names are scratch variables that JShell assigns to any expression that does not have a left-hand side. They persist in the session and can be referenced in later snippets.
Step 3: Define a method. Type "int sq(int n) { return n * n; }". JShell confirms the method was created. Now type "sq(5)". JShell prints "$4 ==> 25". The method lives at the top level of the REPL scope, not inside a class.
Step 4: Define a class inline. Type a multi-line class declaration, ending each line with Enter and the prompt shows "..." until the closing brace is reached. Once the class is defined, you can instantiate it with "var p = new Person("Alice");".
Step 5: Inspect the session state. Type "/vars" to list every variable with its current value, "/methods" to list every method with its signature, "/types" to list every class, interface, and enum, and "/imports" to list every active import. Type "/list" to see the full history of snippets with their numeric IDs.
Step 6: Save, reset, and reload. Type "/save demo.jsh" to write the entire session to disk. Type "/reset" to wipe the session state without leaving JShell. Type "/open demo.jsh" to replay the saved file, restoring every snippet in order.
Java Program for JShell
// This file is a JShell session transcript. To run it, save it as
// demo.jsh and launch `jshell /path/to/demo.jsh` from the terminal.
// Every line is a snippet that JShell evaluates in order.
// --- Variables and expressions ---
int x = 10;
x * 2 + 1
int y = x + 5
y - x
// --- Method definition ---
int square(int n) {
return n * n;
}
square(5)
square(square(2))
// --- Stream and lambda ---
import java.util.stream.IntStream;
IntStream.range(1, 6)
.map(n -> n * n)
.reduce(0, Integer::sum)
// --- Inline class definition ---
class Person {
final String name;
final int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return name + " (" + age + ")";
}
}
Person p = new Person("Alice", 30);
p
p.name
p.age
// --- Mutation and conditional ---
x = 100;
if (x > 50) System.out.println("big"); else System.out.println("small");
// --- Exception handling ---
try {
int z = 1 / 0;
} catch (ArithmeticException ex) {
System.out.println("caught: " + ex.getMessage());
}
// --- Inspect the session ---
/vars
/methods
/list
Code Explanation - Line by Line
The session opens with simple variable declarations and expressions. The line "int x = 10;" is a snippet of VAR kind; JShell stores x as a top-level variable. The line "x * 2 + 1" is an expression snippet; since it has no left-hand side, JShell assigns it to a scratch variable named $2 and prints the result. The same pattern applies to "y - x", which becomes $4 or similar.
The square method is a snippet of METHOD kind. JShell compiles it into a synthetic class internally, but exposes it at the top level of the session so you can call square(5) directly. Calling square(square(2)) demonstrates recursion: JShell first evaluates the inner square(2) to 4, then passes 4 to the outer square, returning 16.
The stream section imports java.util.stream.IntStream because java.util.stream is not in the default import set, then chains range, map, and reduce. The expression returns the sum of squares from 1 to 5, which is 55. The reduce call uses Integer::sum as a method reference, which is shorthand for the lambda (a, b) -> a + b.
The Person class is a snippet of TYPE kind. Because class declarations can span multiple lines, JShell keeps reading after each Enter and prints "..." as the continuation prompt until the closing brace. Once the class is defined, you can instantiate it and call methods on it just like in any Java program. The two expression snippets p and p.name show that JShell prints the toString of any object you reference, which is convenient for inspection.
The mutation snippet "x = 100;" demonstrates that variables declared with int are not final in JShell even though they look like declarations; they can be reassigned. The if-else snippet demonstrates that JShell accepts control flow at the top level, which is impossible in normal Java. The try-catch snippet shows that exceptions thrown inside a snippet are caught and printed by JShell without terminating the session, so you can continue experimenting after an error.
The final three slash commands are not Java at all; they are JShell built-ins. /vars lists every active variable with its current value, /methods lists every method signature, and /list prints every snippet with its numeric ID so you can refer back to it later with /edit ID or /drop ID.
Sample Input and Output
$ jshell demo.jsh x ==> 10 $2 ==> 21 y ==> 15 $4 ==> 5 | created method square(int) $6 ==> 25 $7 ==> 16 $9 ==> 55 | created class Person p ==> Alice (30) $11 ==> "Alice" $12 ==> 30 x ==> 100 big caught: / by zero | int x = 100; | int y = 15; | Person p = Alice (30); | int square(int); | class Person
The transcript shows JShell echoing the value of each snippet in turn. Scratch variables are named $2, $4, $6, $7, $9, $11, $12 in order, while named variables x, y, and p are printed with their identifiers. The class and method creation lines start with the pipe character to distinguish them from value echoes. The output of System.out.println appears inline, intermixed with the snippet echoes. The /vars, /methods, and /list outputs at the bottom show the final state of the session.
Common Mistakes to Avoid
The first mistake is forgetting that JShell wraps snippets in synthetic classes, not in your own class. That means the keyword this inside a top-level method does not refer to anything sensible, and you cannot use the snippet method from another snippet the same way you would call an instance method. The second mistake is leaving a snippet half-typed and pressing Enter inside a multi-line declaration; JShell keeps waiting for the closing brace, and the prompt shows "...". To escape, press Control-C once to cancel the current snippet without leaving the shell.
The third mistake is expecting forward references to work. A method snippet can reference another method that you have not yet defined, because methods are compiled on demand, but a variable snippet cannot reference a variable you have not yet defined. The order of snippets matters; /reset wipes the state when you want to start over. The fourth mistake is using JShell for production code; JShell is a learning and prototyping tool, not a build system. Save the polished snippets into a .java file once they work.
The fifth mistake is assuming that JShell has the same import set as a regular Java program. JShell pre-imports a generous list, but you still need explicit imports for any type outside java.lang, the few common packages listed above, or anything in your own modules. The /imports slash command shows the current list. The sixth mistake is forgetting that the default JShell runs in non-strict mode where many compile-time errors become warnings, which can mask bugs when you later paste the snippet into a real Java file.
Real-World Applications
JShell is used in education to teach Java fundamentals without the friction of a build system, and in IDEs as a scratch pad. IntelliJ IDEA ships a JShell console inside the editor, allowing you to highlight a snippet and press a shortcut to send it to JShell. The same integration is available in Apache NetBeans, Eclipse, and Visual Studio Code via the Java extension pack. JShell scripts are also used in continuous integration pipelines to sanity-check that a freshly built JAR loads and exposes its public API correctly.
In the JDK itself, JShell uses the Java Compiler API and a custom class loader to compile and load snippets on the fly. The same machinery powers the Java Interactive Playground at dev.java, the JBang script runner, and the Skrape.it HTML testing library's REPL mode. In the cloud, AWS Lambda's console uses a similar on-the-fly compilation model to validate inline code. Understanding java 9 jshell repl therefore gives you a fast prototyping loop and a deeper appreciation for how Java code becomes runnable classes. The java 9 jshell repl experience is also the easiest way to demo the modern Java language features to a classroom of new learners.
Conclusion
We showed how to launch JShell, declare variables and methods, define classes inline, use control flow at the top level, and inspect session state with the /vars, /methods, and /list slash commands. JShell is the prototyping tool every Java learner should keep open in a side window, and it is also the gentlest introduction to the Java Compiler API that powers IDE features. The natural next topics to study are the Java 9 module system that JShell runs on top of, and the Java 10 var keyword that JShell supports natively for concise local declarations.
Comments
Comments
Post a Comment