May 12, 2022

JShell in Java

The Java Shell or JShell is an interactive command line tool for learning the Java programming language and to test Java code. JShell is a Read-Evaluate-Print Loop (REPL), which evaluates declarations, statements, and expressions as they are typed and immediately shows the results. This way you don't need to write a full Java class with a main method just for testing some small thing. Many programming languages like Python, Scala already provide such a command shell to execute expressions interactively, with Java 9 even Java has provided a JShell for that purpose.

Usage of JShell

As an example consider a scenario where you have a method of 40-50 lines and as a part of logic of that method you do need to get the month part of the date passed in dd-mm-yyyy format.

While writing this program in IDE your development may involve the following process:

  • Write complete program in IDE.
  • Compile the program
  • Fix any compile time errors.
  • Run the program.
  • Check for run time or logical errors
  • Edit program if any such error found
  • Repeat the process.

Using JShell, you can write program elements one at a time, immediately see the result, and make changes as needed. So, if you want to verify the method for extracting the month part out of the passed date rather than running the whole code and going through the whole elaborate process as showed above you can test that element in JShell to check its correctness. Once you are satisfied it is correct you can copy it to the IDE.

jshell> String getMonth(String date){
   ...> return date.substring(date.indexOf('-') + 1, date.lastIndexOf('-'));
   ...> }
|  created method getMonth(String)

jshell> System.out.println(getMonth("10-05-2020"))
05

How to start JShell

First thing before starting JShell is to ensure that you have JDK 9 or above installed. Also ensure you have Path set so that you can use it from anywhere rather than only from the Java installation directory.

To start JShell, enter the jshell command on the command line.

F:\knpcode>jshell
|  Welcome to JShell -- Version 12.0.1
|  For an introduction type: /help intro

jshell>

You can also start JShell in verbose mode using the –v option.

F:\knpcode>jshell -v
|  Welcome to JShell -- Version 12.0.1
|  For an introduction type: /help intro

jshell>

Stopping the JShell

To exit JShell, enter /exit.
jshell> /exit
|  Goodbye

F:\knpcode>

Printing hello world message

Now when you have started a JShell session let’s start by printing the "Hello World" message.

jshell> System.out.println("Hello world from JShell");
Hello world from JShell

Declaring variables in JShell

You can declare variables in JShell in the usual way. Note that a variable once declared can be used throughout the session.

For example declaring an int variable

jshell> int i = 10
i ==> 10
|  created variable i : int

Since the session is started with verbose mode so it is printing a full description of what has occurred.

The value of the variable is retained thought out the session. You can test that by printing the value of i.

jshell> System.out.println(i)
10

You can change the type of the variable even in incompatible ways in JShell. For example with in the same session of JShell type of i can be changed from int to String.

jshell> String i = "test";
i ==> "test"
|  replaced variable i : String
|    update overwrote variable i : int

jshell>

Another thing to note here is that in some of the expressions semicolon is not there. JShell automatically adds terminating semicolons to the end of a complete snippet if not entered.

Scratch Variables in JShell

If you enter an expression that is not assigned to a named variable a scratch variable is created automatically to store the value so that the value can be referenced later. Scratch variables start with a '$' sign.

jshell> 3+ 4
$8 ==> 7
|  created scratch variable $8 : int

jshell> System.out.println($8);
7

Methods in JShell

You can write a method in JShell and call it from JShell to test it immediately.

jshell> int add(int a, int b){
   ...> return a + b;
   ...> }
|  created method add(int,int)
jshell> add(5,4)
$11 ==> 9
|  created scratch variable $11 : int

Forward References in JShell

In JShell you can write a method that reference methods, variables, or classes that aren’t yet defined. For example consider the following method.

jshell> void arithmetic(int a, int b){
   ...> int sum = add(a, b);
   ...> System.out.println("Sum is " + sum);
   ...> int product = multiply(a, b);
   ...> System.out.println("Product is " + product);
   ...> }
|  created method arithmetic(int,int), however, it cannot be invoked until method multiply(int,int) is declared

As you can see JShell has allowed the definition of arithmetic method but with the warning that multiply() method which is referenced by arithmetic() method should be declared before it can be invoked. Note that add() method is already defined so no warning for that.

You can test it by trying to execute the arithmetic method which fails because required element is missing.

jshell> arithmetic(5, 6)
|  attempted to call method arithmetic(int,int) which cannot be invoked until method multiply(int,int) is declared

Once you define the multiply() method then arithmetic() method can be called.

jshell> int multiply(int a, int b){
   ...> return a * b;
   ...> }
|  created method multiply(int,int)
|    update modified method arithmetic(int,int)
jshell> arithmetic(5, 6)
Sum is 11
Product is 30

Define Classes in JShell

You can also define a class in JShell.

jshell> class HelloWorld{
   ...> void display(){
   ...> System.out.println("Hello World");
   ...> }
   ...> }
|  created class HelloWorld

Then call it like this-

jshell> new HelloWorld().display();
Hello World

JShell Commands

JShell commands control the environment and display information within a session. Any JShell command starts with a leading forward slash (/) which distinguishes it from snippets.

Getting list of available commands

You can get the list of available JShell commands by typing forward slash (/) and then tab.

jshell> /
/!          /?          /drop       /edit       /env        /exit
/help       /history    /imports    /list       /methods    /open
/reload     /reset      /save       /set        /types      /vars

If you press tab again it gives a small description of each command.

/vars command List the declared variables and their values.
jshell> /vars
|    String x = "test"
|    String i = "test"
|    int $8 = 7
|    int $11 = 9
/methods Command

List the declared methods and their signatures

jshell> /methods
|    int add(int,int)
|    void arithmetic(int,int)
|    int multiply(int,int)
/list Command

List the source you have typed

jshell> /list

   1 : System.out.println("Hello world from JShell");
   3 : System.out.println(i)
   4 : String x = "test";
   6 : System.out.println(i);
   7 : String i = "test";
   8 : 3+ 4
   9 : System.out.println($8);
  10 : int add(int a, int b){
       return a + b;
       }
  11 : add(5,4)
  13 : void arithmetic(int a, int b){
       int sum = add(a, b);
       System.out.println("Sum is " + sum);
       int product = multiply(a, b);
       System.out.println("Product is " + product);
       }
  14 : arithmetic(5, 6)
  15 : int multiply(int a, int b){
       return a * b;
       }
  16 : arithmetic(5, 6)
  17 : class HelloWorld{
       void display(){
       System.out.println("Hello World");
       }
       }
  18 : new HelloWorld().display();
/imports Command

List the imported items, note that JShell imports few packages by default even if you don’t import any package explicitly.

jshell> /import
|    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.*
/help Commamd

Get information about using the jshell tool

/exit Command

Exit the jshell tool

That's all for the topic JShell in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment