Java 9 JShell

Java 9 JShell Command line tool.

The Java 9 JShell tool allows you to write and evaluate Java expressions, statements and declarations on the command line via an interactive tool. To start JShell type in ‘jshell’ on the command line. If that does not work, make sure you have installed JDK 9 or 10 and the bin folder is in classpath. The tool can be primarily used to quickly prototype functions and classes without going through the whole cycle of build, compile and run. Let’s look at some of JShell commands and concepts.

JShell Snippet

A JShell snippet is code that is written in jshell and evaluated independently. It can refer to a variable, method or class declaration, or an actual method call. Here are some examples

int x = 3

This declares an int variable called x. To list all variables use the command /vars>. To declare a class with a static method

public class Test {
public static int sum(int x, int y) {
   return x+y;
}
}

This is how the sum method is run

Test.sum(2,3)

JShell Commands

To list all the methods use /methods and to list all classes use /types.

JShell imports some packages and classes by default. To look at current imports type in </imports. A new import can be directly specified.
To list all the snippets entered so far use the /list command.

JShell Editor

JShell allows editing snippets in an external editor. To specify and editor type in

/set editor vim

To edit snippets type in /edit. To edit a particular snippet type in /edit [snippet_no] . Each snippet is given a number and that number can be use to reference the snippet

JShell shortcuts

JShell defines four shortcuts.

  • Tab – use the tab to autocomplete types, method suggestions or variables.
  • Use Shift+Tab followed by i to auto import. For example, When using java nio PIPE, we need to import the PIPE class. if you type in new PIPE followed by Shift+Tab and i, the tool will suggest imports
    jshell> JFrame
    0: Do nothing
    1: import: javax.swing.JFrame
    Choice: 
    Imported: javax.swing.JFrame
    
  • Shift+tab followed by v can be used to create a variable. In the example above if we fire this command after new JFrame, the tool allows use to define a new jframe variable
    jshell> new JFrame()
    jshell> JFrame jframe = new JFrame()
    
  • Shift+Tab followed by m can be used to create a method from an expression.
    jshell> 2+3
    jshell> int |() { return 2+3; }
    

    enter the name of the method where the cursor(|) is.

Leave a Comment