How to import external libraries in JShell in Java 9?



In this article, we will learn to import external libraries in JShell in Java 9. JShell is an interactive tool to learn the Java language and prototype Java code. This tool works on the principle of REPL (Read-Evaluate-Print-Loop).

Default Imports in JShell

By default, JShell automatically imports a few useful Java packages when the JShell session is started. We can type the command /imports to get a list of all these imports.

jshell> /imports
| import java.io.*
| import java.math.*
| import java.net.*
| import java.nio.file.*
| import java.util.*
| import java.util.concurrent.*
| import java.util.function.*
| import java.util.prefs.*
| import java.util.regex.*
| import java.util.stream.*
| import javax.mail.internet.InternetAddress

Importing External Libraries in JShell

We can also import external libraries in JShell by using the steps below:

If we want to create an InternetAddress object that resides in the javax.mail.internet package, then we need to import that package in JShell.

jshell> import javax.mail.internet.InternetAddress
| Error:
| package javax.mail.internet does not exist
| import javax.mail.internet.InternetAddress;
| ^---------------------------------^

In the above, just importing the class doesn't work because the package is unknown to the classpath.

Add the JAR to the classpath

We need to add jars or class files to the classpath by using the command: "/env -class-path <jars, class files>".

jshell> /env --class-path \Users\user\mail-1.4.7.jar
| Setting new options and restoring state.

Verifying Classpath Changes

To verify that the JAR files have been added to the classpath correctly, we can list the current classpath.

jshell> /env
| javax.class.path: .
|     \Users\user\mail-1.4.7.jar

Importing the InternetAddress

After verifying that the jar is added to the classpath, we can now import the InternetAddress class from the javax.mail.internet package that is available for use in the current session.

jshell> import javax.mail.internet.InternetAddress

Using the InternetAddress Class

Finally, we can create an InternetAddress object by using below:

jshell> InternetAddress from = new InternetAddress("a@a")
from ==> a@a
Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-06-10T18:42:54+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements