
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to save, edit, and drop a snippet in JShell in Java 9?
Java Shell or JShell is an official REPL(Read-Evaluate-Print-Loop) introduced with Java 9. It provides an interactive shell for quickly prototyping, debugging and without the need for the main() method or the need to compile the code before executing it. JShell is easily started by typing "jshell" in the command prompt.
What are Snippets?
JShell allows the execution of Java statements, variables, methods, class definitions, imports, and expressions. These pieces of Java code are referred to as snippets. Every snippet is assigned an ID(unique) that we can use later to reference it.
Example
Below is an example to represent a snippet to add two integers:
jshell> int sum(int a, int b) { return a + b; } | created method sum(int,int)
Save a snippet
We can save a snippet source to a file by using the "/save [-all|-history|-start] " command.
Save Modes
The following are some common JShell save modes:
-
/save-all: Saves all snippets, including those that failed.
-
/save-history: Saves just the history of commands.
- /save-start: Saves the startup snippets.
Syntax
The following is the syntax for saving a snippet:
/save <filename-location>
Example
Below is an example for saving a snippet:
C:\Users\User>jshell | Welcome to JShell -- Version 9.0.4 | For an introduction type: /help intro jshell> /save C:\Users\User\jshell.txt
The above code creates a new "jshell.txt under the specified path.
Edit a snippet
We can also edit the code in an external editor by using the "/edit" command.
Syntax
The following is the syntax for editing a snippet:
/edit <snippet-name-or-id>
Example
Below is an example for editing a snippet:
C:\Users\User>jshell | Welcome to JShell -- Version 9.0.4 | For an introduction type: /help intro jshell> /edit | created method empName(String,String)
Output
This launches the JShell edit pad, where we can edit the code snippet and save it.
Jshell Edit Pad
Drop a snippet
Similarly, we can also drop a particular snippet by using the command "/drop".
Syntax
The following is the syntax to drop a snippet:
/drop <id>
Dropping All Snippets
Dropping all snippets means it clears all snippets in the current session and resets the JShell state.
Syntax
The following is the syntax for dropping all snippets a snippet:
/reset
Example
Below is an example to drop a snippet:
jshell> /drop 1
| dropped method empName(String,String)
The above command tells the JShell to drop the snippet with ID 1 from your current session. To check if the ID is dropped, run the "/list" command on the JShell, it will show all the active snippets.