Tutorial on JShell in Java
JShell is an interactive command-line tool introduced in Java 9 that allows developers to quickly test code snippets, explore API features, and interact with the Java programming language without the need to write a full-fledged class or method. It’s part of the REPL (Read-Eval-Print Loop) system, making it perfect for beginners and experienced developers alike for testing or prototyping Java code.
This tutorial will guide you through the basics and advanced usage of JShell to help you get the most out of it.
1. Introduction to JShell
What is JShell?
JShell provides a REPL environment for Java. You can enter Java statements, expressions, and methods, and JShell will evaluate them immediately and print the result. This is particularly useful for:
- Trying out new Java APIs.
- Testing small code snippets.
- Rapid prototyping.
- Learning Java interactively.
JShell eliminates the need for writing boilerplate code (like creating a `main()` method or class) to test simple logic.
Launching JShell
To start JShell, you must have Java 9 or higher installed. Use the command below in command prompt to launch it:
jshellUpon launching, you will see a prompt like:
| Welcome to JShell - Version 15.0.2
| For an introduction type: /help intro
jshell>You are now in the interactive JShell environment.
2. Basic Operations in JShell
Evaluating Expressions
You can enter simple expressions, and JShell will immediately evaluate and return the result.
jshell> 2 + 3
$1 ==> 5In the above example:
- `jshell>` is the prompt.
- `$1` is the auto-generated variable storing the result of the expression.
- `5` is the result of the expression `2 + 3`.
Working with Variables
You can define variables without writing a class or method. JShell allows dynamic type inference.
jshell> int x = 10;
x ==> 10
jshell> var y = 20;
y ==> 20
jshell> x + y
$2 ==> 30- `var` lets you declare a variable with inferred type.
- You can use these variables interactively.
Using Methods
JShell allows you to define and invoke methods directly.
jshell> int add(int a, int b) {
…> return a + b;
…> }
| created method add(int,int)
jshell> add(5, 3)
$3 ==> 8You can now define methods interactively and call them immediately
3. Working with Classes and Objects
Defining Classes
You can define classes inside JShell and instantiate objects without needing to save and compile an entire Java file.
jshell> class Person {
…> String name;
…> int age;
…>
…> Person(String name, int age) {
…> this.name = name;
…> this.age = age;
…> }
…>
…> void sayHello() {
…> System.out.println("Hello, my name is " + name);
…> }
…> }
| created class Person
jshell> Person p = new Person("John", 25);
p ==> Person@1b6d3586
jshell> p.sayHello()
Hello, my name is JohnJShell allows full class definitions, including constructors, fields, and methods, just like in a regular Java program.
Modifying Classes
You can re-declare classes, methods, or variables in JShell without having to restart the environment. This makes it perfect for prototyping.
jshell> class Person {
…> String name;
…> int age;
…>
…> Person(String name, int age) {
…> this.name = name;
…> this.age = age;
…> }
…>
…> void sayGoodbye() {
…> System.out.println("Goodbye from " + name);
…> }
…> }
| modified class Person
jshell> p.sayGoodbye()
Goodbye from John4. Exploring JShell Commands
JShell comes with several built-in commands to help manage the REPL environment. All JShell commands begin with a `/`.
/help: List Available Commands
Typing `/help` provides a list of all available commands in JShell.
jshell> /help/vars: List Variables
The `/vars` command shows all defined variables in the current session.
jshell> /vars
| int x = 10
| var y = 20
| var p = Person@1b6d3586/methods: List Defined Methods
The `/methods` command shows all defined methods.
jshell> /methods
| int add(int,int)
| void Person.sayGoodbye()/types: List Classes and Interfaces
The `/types` command lists all defined classes and interfaces.
jshell> /types
| class Person/list: List All Code Entered
The `/list` command shows a history of all the code you’ve typed.
jshell> /list
1 : int x = 10;
2 : var y = 20;
3 : int add(int a, int b) { return a + b; }
4 : class Person { … }/edit: Edit Code Snippets
If you want to modify a previous code snippet, use the `/edit` command followed by the snippet number:
jshell> /edit 3/drop: Drop Variables, Methods, or Classes
Get Pratik T’s stories in your inbox
Join Medium for free to get updates from this writer.
You can drop specific variables, methods, or classes if you no longer need them using the `/drop` command.
jshell> /drop x
| dropped variable x/save: Save Session to a File
The `/save` command allows you to save the current session to a file for later use.
jshell> /save mySession.jsh/open: Load Session from a File
To load a previously saved session, use `/open`.
jshell> /open mySession.jsh5. Importing External Libraries and Classes
You can import standard and external libraries just like you would in a normal Java program. This allows you to work with classes from the Java API and other libraries.
jshell> import java.util.List;
jshell> List.of(1, 2, 3)
$4 ==> [1, 2, 3]You can also import external libraries using their JAR files.
jshell> /env -class-path lib/external-library.jarThis is useful when you want to experiment with third-party libraries like Apache Commons, Google Guava, etc.
6. JShell Snippets
JShell introduces the concept of snippets. Each input you type (like a variable declaration, a method, or an expression) is considered a snippet. Snippets can be referred to, re-used, or dropped using commands like `/vars`, `/methods`, `/types`, `/list`, etc.
Modifying Snippets
You can use the `/edit` command to modify a previously entered snippet. For example:
jshell> /edit 3This allows interactive experimentation by changing previously entered code.
7. Using JShell for Prototyping and Testing
Rapid Prototyping
JShell is perfect for rapid prototyping, where you can test different components of your code before embedding them in a larger application.
For example, you can experiment with new Java features, such as the Streams API, Lambda Expressions, and Optional:
jshell> var list = List.of(1, 2, 3, 4, 5);
list ==> [1, 2, 3, 4, 5]
jshell> list.stream().filter(i -> i % 2 == 0).forEach(System.out::println);
2
4Testing Code Snippets
JShell is also useful for testing small snippets of code, especially for checking if your logic works as expected:
jshell> int factorial(int n) {
…> if (n == 0) return 1;
…> return n factorial(n - 1);
…> }
| created method factorial(int)
jshell> factorial(5)
$5 ==> 1208. Integrating JShell with IDEs
Most modern Java IDEs like IntelliJ IDEA, Eclipse, and NetBeans have built-in support for JShell. This integration allows you to use JShell within your development environment, which is particularly useful when working on larger projects and you want to test code snippets on the fly.
IntelliJ IDEA
In IntelliJ IDEA:
- Open JShell by navigating to `Tools` -> `JShell Console`.
- You can use it just like you would from the command line.
Eclipse
In Eclipse:
- Install the Eclipse Java Development Tools (JDT) if it’s not already available.
- You can open the JShell console and interact with it.
9. Advanced Usage of JShell
Customizing JShell with Startup Scripts
You can customize the JShell startup environment by writing a startup script that defines variables, imports classes, and loads external JAR files automatically.
Example startup script `startup.jsh`:
import java.util.;
import java.time.;
var list = List.of("One", "Two", "Three");
var now = LocalDate.now();
System.out.println("JShell started with custom script");To start JShell with the custom script:
jshell - startup startup.jshJShell with External Libraries
You can extend JShell with external JAR files using the `/env -class-path` command, enabling the use of third-party libraries for interactive testing.
Example:
jshell> /env -class-path libs/commons-lang3–3.11.jarThis will allow you to work with the Apache Commons Lang library in your JShell session.
10. Exiting and Saving Sessions
Exiting JShell
To exit JShell, use the `/exit` command:
jshell> /exitSaving Your Work
You can save your JShell session to a file for later use:
jshell> /save mysession.jshThis saves the state of the session, including all variables, methods, classes, and snippets.
Conclusion
JShell is an incredibly powerful tool that simplifies Java development by providing a fast and efficient way to test code, explore new APIs, and learn Java interactively. It is perfect for rapid prototyping, learning, and debugging, making it a valuable tool for both beginners and experienced Java developers.
Next Steps:
- Experiment with different Java APIs using JShell.
- Use JShell for prototyping complex algorithms or working with new libraries.
- Learn more about advanced commands like `/reload`, `/reset`, and `/classpath` for better session management and customization.









