Java 9: Introducing JShell

The first post in the series of Java 9, which I  announced a few weeks ago, will be about JShell. JShell is the REPL (Read-Eval-Print loop) tool for the Java language. The tool allows you to test snippets of code outside of your IDE. In this introduction, we will explore some of the features of JShell.

Precondition

  1. Since JShell is introduced with Java 9, a prerequisite is to have Java 9 installed 😉
  2. If the bin directory is not in your path, you will have to navigate to the <Java 9 installation directory>\bin , in order to start JShell via the command line.

Start and stop JShell

  1. Type ‘jshell’ in the command line from the bin-directory. JShell is started and the following text is shown:
    |  Welcome to JShell -- Version 9
    |  For an introduction type: /help intro
  2. If you want to exit JShell, just type ‘/exit’

Create single statements

  1. In the first example, we add the values of two variables.
    1. Create the first variable:
      jshell> int i = 4
      i ==> 4
    2. Create the second variable:
      jshell> int j = 5
      j ==> 5
    3. Then add both variables:
      jshell> i + j
      $3 ==> 9
    4. Some interesting things are:
      1. no semi-colon is needed when you want to execute a single statement.
      2. for the calculation a dummy variable is created automatically. If you enter ‘i’, then the value of ‘4’ is printed, if you enter ‘$3’, the value of ‘9’ is printed.
  2. In the second example, we execute the Thread.sleep() method. We all know that this should be surrounded with a try-catch, but in JShell this is not necessary:
    Thread.sleep(1000)

Create methods

  1. Let’s create an add method:
    jshell> int add(int i, int j) {
    ...> return i + j;
    ...> }
    |  created method add(int,int)
  2. Some interesting things are:
    1. a semi-colon is now necessary, for single statements we could omit the semi-colon.
    2. the continuation prompt ‘…>’ is shown, which tells us that more than one line is necessary to complete the snippet.
  3. Now we can use the method:
    jshell> add(3,5)
    $8 ==> 8
  4. It is also possible to rerun the previous command:
    jshell> /!
    add(3,5)
    $9 ==> 8

Other useful commands

  1. The first useful command is tab-completion. Use it wherever you can, it saves you typing. You can also use the up and down arrows to browse the history of commands you entered.
  2. Show all variables with command ‘/v’:
    jshell> /v
    int i = 4
    int j = 5
    int $3 = 9
    int $8 = 8
    int $9 = 8
  3. Show all methods with command ‘/m’:
    jshell> /m
    int add(int,int)
  4. Edit the previous entered commands with command ‘/edit’. The JShell Edit Pad will be opened:
    jshelleditpad
  5. Change the value of i into ‘1’ and click the ‘Accept’ button. The JShell console output shows:
    i ==> 1
  6. Change the add method into the following and click the ‘Accept’ button:
    int substract(int i, int j) {
      return i - j;
    }
  7. When we show the list of methods, then both the ‘add’ method and the ‘substract’ method are shown. Opening the JShell Edit Pad again, shows the re-assignment of variable i and the creation of the ‘substract’ method.
  8. The command ‘/list’ shows the list of commands we entered. It shows us basically the same information as with the ‘/edit’ command.
  9. The command ‘/reset’ resets the state of the JShell command window. Executing ‘/list’ after a reset, shows no commands.
  10. With command ‘/drop’, it is possible to drop a variable or method:
    jshell> int i = 4
    i ==> 4
    jshell> int j = 5
    j ==> 5
    jshell> /v
    i ==> 4
    j ==> 5
    jshell> /drop i
    dropped variable i
    jshell> /v
    j ==> 5

Save and restore commands

  1. With the command ‘/save <file>’ it is possible to store the commands you entered into a file. Beware that you have sufficient access rights (by default the file will be stored into the bin directory if you omit the path):
    jshell> /save d:\examples\example.jsh
  2. For test, reset the JShell state with the command ‘/reset’.
  3. Check the output of ‘/list’, it should be empty.
  4. Now, open the previous created jshell file:
    jshell> /open d:\examples\example.jsh
  5. Run ‘/list’ again, and the output shows the commands from the example.jshell

Create classes

Classes can be created, just like methods.

  1. Create a class SendEmail just like you would do in an IDE, except without the imports.
    jshell> public class SendEmail {
     ...> public void setRecipient(String recipient) {
     ...> System.out.println("Recipient is " + recipient);
     ...> }
     ...> }
    | created class SendEmail
  2. With the command ‘/t’, a list of created classes is shown.
    jshell> /t
    | class SendEmail
  3. The class can be used to create objects.
    jshell> SendEmail mail = new SendEmail();
    mail ==> SendEmail@50b494a6
  4. And of course the methods can be invoked.
    jshell> mail.setRecipient("a@a.a")
    Recipient is a@a.a

Use external classes

The above examples are pretty straightforward and easy and make use of standard Java classes. But often you would like to use classes from external libraries or self written classes. In the example we will use the JavaMail library as external library.

  1. Let’s say we want to create an InternetAddress object which resides in the javax.mail.internet package. All we have to do is to import the package just as we would when writing a Java class.
    jshell> import javax.mail.internet.InternetAddress
    | Error:
    | package javax.mail.internet does not exist
    | import javax.mail.internet.InternetAddress;
    |        ^---------------------------------^
  2. As we see, just importing the class will not work because the package is unknown to the classpath. Adding jars or class files to the classpath can be achieved with ‘/env –class-path <jars, class files>’.
    jshell> /env --class-path <path to jarfile>\mail-1.4.7.jar
    | Setting new options and restoring state.
    jshell> import javax.mail.internet.InternetAddress
  3. At this moment, we can create InternetAddress objects
    jshell> InternetAddress from = new InternetAddress("a@a.a")
    from ==> a@a.a

This concludes the first post about Java 9. JShell is a handy tool when you quickly want to test or show some things without setting up a complete Java project.

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.