Java JShell

Introduction

JShell, introduced in Java 9, is a Read-Eval-Print Loop (REPL) tool that allows developers to interactively evaluate Java code snippets. JShell provides a quick and easy way to test and explore Java code without the need for a full development environment. It is particularly useful for prototyping, learning, and testing small pieces of code.

Key Points:

  • Interactive Shell: Allows for immediate feedback and interactive exploration of Java code.
  • Prototyping: Quickly test and prototype Java code snippets.
  • Learning Tool: Great for learning Java and experimenting with new APIs.

Table of Contents

  1. Starting JShell
  2. Basic Commands
  3. Working with Variables
  4. Defining Methods
  5. Importing Packages
  6. Using External Libraries
  7. Saving and Loading Sessions
  8. Practical Examples
  9. Conclusion

1. Starting JShell

To start JShell, open a terminal and type jshell. This will launch the JShell interactive prompt.

Example:

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

jshell>

2. Basic Commands

JShell provides several built-in commands to help you manage your session. These commands start with a forward slash (/).

Common Commands:

  • /help: Displays help information.
  • /vars: Lists all declared variables.
  • /methods: Lists all declared methods.
  • /list: Lists all snippets (code entered so far).
  • /save: Saves the current session to a file.
  • /open: Opens a file and loads its contents into the session.
  • /exit: Exits JShell.

Example:

jshell> /help
|  Type a Java language expression, statement, or declaration.
|  Or type one of the following commands:
|  /exit                   -- Exit jshell
|  /help                   -- Display this help message
|  /vars                   -- List the declared variables and their values
|  /methods                -- List the declared methods and their signatures
|  /list                   -- List the source of all snippets
|  /save [file]            -- Save the current state to a file
|  /open <file>            -- Open a file as a jshell session

3. Working with Variables

You can declare and use variables in JShell just like you would in a Java program.

Example:

jshell> int x = 10;
x ==> 10

jshell> x
$1 ==> 10

jshell> x + 5
$2 ==> 15

jshell> String message = "Hello, JShell!";
message ==> "Hello, JShell!"

jshell> message
$3 ==> "Hello, JShell!"

Explanation:

  • int x = 10;: Declares an integer variable x with the value 10.
  • x: Retrieves the value of x.
  • x + 5: Evaluates an expression using x.
  • String message = "Hello, JShell!";: Declares a string variable message.

4. Defining() Methods

You can define methods in JShell and call them interactively.

Example:

jshell> void greet() {
   ...>     System.out.println("Hello from JShell!");
   ...> }
|  created method greet()

jshell> greet();
Hello from JShell!

Explanation:

  • void greet() { … }: Defines a method named greet that prints a message.
  • greet();: Calls the greet method.

5. Importing Packages

You can import Java packages and use their classes and methods in JShell.

Example:

jshell> import java.util.ArrayList;

jshell> ArrayList<String> list = new ArrayList<>();
list ==> []

jshell> list.add("Java");
$4 ==> true

jshell> list.add("JShell");
$5 ==> true

jshell> list
$6 ==> [Java, JShell]

Explanation:

  • import java.util.ArrayList;: Imports the ArrayList class.
  • ArrayList list = new ArrayList<>();: Creates an ArrayList of strings.
  • list.add("Java");: Adds an element to the list.
  • list: Displays the contents of the list.

6. Using External Libraries

You can use external libraries in JShell by specifying the classpath.

Example:

$ jshell --class-path path/to/library.jar

Explanation:

  • –class-path path/to/library.jar: Specifies the classpath to include the external library.

7. Saving and Loading Sessions

You can save your JShell session to a file and load it later.

Example:

jshell> /save mysession.jsh
|  State saved to: mysession.jsh

jshell> /exit
$ jshell> /open mysession.jsh
|  Restoring state from mysession.jsh

Explanation:

  • /save mysession.jsh: Saves the current session to a file named mysession.jsh.
  • /open mysession.jsh: Loads the session from the mysession.jsh file.

8. Practical Examples

Example 1: Calculating the Sum of an Array

jshell> int[] numbers = {1, 2, 3, 4, 5};
numbers ==> int[5] { 1, 2, 3, 4, 5 }

jshell> int sum = 0;
sum ==> 0

jshell> for (int number : numbers) {
   ...>     sum += number;
   ...> }
sum ==> 15

jshell> sum
$7 ==> 15

Example 2: Reversing a String

jshell> String str = "Java";
str ==> "Java"

jshell> String reversed = new StringBuilder(str).reverse().toString();
reversed ==> "avaJ"

jshell> reversed
$9 ==> "avaJ"

9. Conclusion

JShell is used for Java developers, providing an interactive environment for testing, learning, and prototyping Java code. By using JShell, you can quickly experiment with code snippets, test new APIs, and validate your ideas without the overhead of setting up a full development environment. Understanding the basic commands and capabilities of JShell can significantly enhance your productivity and learning experience.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top