JShell is an interactive Java Shell (Read-Eval-Print Loop or REPL) introduced in Java 9, which allows developers to quickly prototype, explore, and learn Java concepts without the overhead of writing and compiling a full Java program. In this comprehensive guide, we’ll cover everything you need to know about JShell, from starting your first JShell session to advanced features and tips for maximizing your productivity.
Installing JShell
JShell comes bundled with the Java Development Kit (JDK) version 9 or later. To use JShell, you need to have JDK 9 or a later version installed on your system. See Installing the Java Development Kit (JDK).
Launching JShell
To start a JShell session, open your terminal or command prompt and type jshell. This will launch the JShell prompt, where you can begin writing Java expressions, statements, and declarations.
$ jshell
| Welcome to JShell -- Version 18
| For an introduction type: /help intro
jshell>
Code language: Java (java)
Basic JShell Usage
Writing and Executing Code
In JShell, you can write and execute Java code snippets without needing to create a complete Java program. You can write expressions, statements, variable declarations, methods, and even classes directly in the JShell prompt.
Example:
jshell> 2 + 3
$1 ==> 5
Code language: Java (java)
JShell automatically assigns a generated variable name (e.g., ‘$1
‘) for the result of an expression if you don’t provide a variable name.
Declaring Variables and Methods
You can declare variables and methods in JShell just like you would in a Java program. When declaring a method, you don’t need to enclose it within a class.
Example:
jshell> int x = 10
x ==> 10
jshell> int square(int n) {
...> return n * n;
...> }
| created method square(int)
Code language: Java (java)
Using Built-in JShell Commands
JShell provides several built-in commands that start with a forward slash /. These commands help you manage your JShell session and interact with your code snippets.
Some common JShell commands include:
- ‘
/help
‘: Displays help information. - ‘
/list
‘: Lists all the code snippets you’ve entered. - ‘
/save <filename>
‘: Saves your code snippets to a file. - ‘
/open <filename>
‘: Loads code snippets from a file. - ‘
/reset
‘: Resets the JShell session, clearing all variables, methods, and imports. - ‘
/exit
‘: Exits JShell.
Advanced JShell Features
Tab Completion and Suggestions
JShell supports tab completion, which allows you to quickly complete method names, variable names, and JShell commands by pressing the ‘Tab
‘ key.
Example:
jshell> String greeting = "Hello, World!"
greeting ==> "Hello, World!"
jshell> greeting.toUpper<Tab>
greeting.toUpperCase()
Code language: Java (java)
Editing Code Snippets
JShell makes it easy to edit your code snippets using the /edit command. This command opens a simple editor where you can modify your code. You can also configure JShell to use your preferred external editor by setting the ‘JDK_JAVA_OPTIONS
‘ environment variable.
Example:
jshell> /edit square
Code language: Java (java)
This command opens the ‘square
‘ method in the default editor, where you can edit and save your changes. Once you save your changes and close the editor, JShell will automatically reload and recompile the updated method.
Automatic Imports
JShell automatically imports several commonly used Java classes, such as ‘java.util.*’ ‘java.io.*’, and ‘java.math.*’, so you don’t have to manually import them each time you start a new session.
Example:
jshell> List<String> names = new ArrayList<>();
names ==> []
jshell> names.add("Alice");
$2 ==> true
Code language: Java (java)
You can also import additional packages and classes using the ‘import
‘ statement, just like in a regular Java program.
Exception Handling
JShell supports exception handling using try-catch blocks, allowing you to handle errors gracefully during your interactive sessions.
Example:
jshell> int divide(int a, int b) {
...> if (b == 0) {
...> throw new IllegalArgumentException("Cannot divide by zero");
...> }
...> return a / b;
...> }
| created method divide(int,int)
jshell> try {
...> System.out.println(divide(10, 2));
...> System.out.println(divide(10, 0));
...> } catch (IllegalArgumentException e) {
...> System.out.println(e.getMessage());
...> }
5
Cannot divide by zero
Code language: Java (java)
Tips and Tricks
Creating and Using Initialization Scripts
To save time and maintain a consistent JShell environment, you can create initialization scripts that load frequently used methods, classes, and imports each time you start a new session. Create a new text file with the .jsh
extension (e.g., my-init-script.jsh
). Add your custom code to the file, such as commonly used imports, utility methods, or class definitions. For example:
// Import frequently used packages
import java.util.*;
import java.io.*;
import java.time.*;
// Define custom utility methods
public static int multiply(int a, int b) {
return a * b;
}
// Add class definitions
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Additional methods and fields
}
Code language: Java (java)
Save the file and close the text editor. Start JShell with the ‘–startup’ option followed by the path to your initialization script:
$ jshell --startup my-init-script.jsh
Code language: Java (java)
JShell will automatically load the specified imports, methods, and classes from the initialization script when it starts, making them available for use in your session.
Working with External Libraries
You can use external libraries in JShell by adding them to the classpath when starting a new session. Use the ‘--class-path
‘ option or the shorthand ‘-cp
‘ followed by the path to the JAR file or directory containing the library classes.
For example, to use the popular library Gson in JShell, download the Gson JAR file and run JShell with the ‘--class-path
‘ option:
$ jshell --class-path gson-2.8.9.jar
Code language: Java (java)
Once JShell starts, you can import and use the Gson library classes as usual.
Command History
JShell maintains a command history, allowing you to easily access previously executed commands using the up and down arrow keys. This feature is helpful when you want to modify and re-run a command without having to type it out again.
Resetting the JShell Environment
If you need to reset your JShell environment during a session, use the ‘/reset
‘ command. This command clears all imported packages, defined methods, and created variables, returning JShell to its initial state.
jshell> /reset
| Resetting state.
Code language: Java (java)
By leveraging these tips and tricks, you can enhance your productivity and streamline your workflow when working with JShell.