How to load a file into the JShell session in Java 9?



In this article, we will learn to load a file into the JShell session in Java 9. We will learn about Jshell and different ways we can load a file in Jshell, which is the command line and the /open command.

What is a JShell?

JShell is a new command-line interactive REPL (Read-Evaluate-Print-Loop) tool introduced in Java 9 to evaluate declarations, statements, and expressions written in Java. This tool also allows us to execute Java code snippets and get immediate results.

Loading a file into the JShell

There are two ways to load a file into the JShell session in Java 9:

Using command-line

Sometimes, we have the code already written in a Java file and are ready to execute it in JShell. We can run that code within the JShell by loading a file directly using the command-line.

For instance, I have created the "Test1.java" file in the "c://temp" folder.

Below is the code of the "Test1.java" file:

class TutorialsPoint
{
    public static void main(String[] argsv)
    {
    }

    public static void doSomething()
    {
        System.out.println("Welcome to Tutorials Point");
    }
}

Example

Below is a code snippet for loading a file into the JShell using the command-line:

c:\temp>jshell Test1.java
|  Welcome to JShell -- Version 9.0.4
|  For an introduction type: /help intro

jshell> TutorialsPoint.doSomething()
Welcome to Tutorials Point

In the code snippet, the "Test1.java" file is directly loaded from the command-line, and the doSomething() function is called from the TutorialsPoint method to print "Welcome to Tutorials Point".

Using /open command

To load a file into the JShell tool, we can use the "/open" command. Files are executed in the order they are entered in the JShell session.

For instance, I have created the "Test2.java" file in the "c://temp" folder. We can load the "Test2.java" file into JShell by using the "/open" command.

Below is the code of the "Test2.java" file:

String s1 = "TutorialsPoint";
String s2 = "Tutorix";
String s3 = s1 + s2;

int sum(int a, int b) {
   return a + b;
}

int divide(int a, int b) {
   return a / b;
}

Example

Below is a code snippet for loading a file into the JShell using the "/open" command:

C:\Users\User>jshell
| Welcome to JShell -- Version 9.0.4
| For an introduction type: /help intro

jshell> /open c:\temp\Test2.java

jshell> /vars
|    String s1 = "TutorialsPoint"
|    String s2 = "Tutorix"
|    String s3 = "TutorialsPointTutorix"

jshell> /methods
|    int sum(int,int)
|    int divide(int,int)

The "/open" command has loaded the "Test2.java" file into a session. The "/vars" command can be used to load the variables into a session and "/methods" command can be used to load the methods into a session.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-06-09T19:30:05+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements