Thursday, 12 October 2017

Jshell (JAVA + REPL)

If I really want to figure out how a class or method works, I prefer to experiment directly with the code. Unlike documentation, code never lies. Also, programming is best learned by programming. The jshell is the ideal solution for this. I’ve always been annoyed by the overhead necessary to “briefly” run a few lines of code. With the jshell it’s so much simpler now — people should go try it for themselves right now!
                                                                                                     --Marcus Biel

Brief Table of Content
  • Introduction to JShell
  • Running JShell
  • JShell Default imports
  • JShell configurations
  • JShell Expressions
  • JShell Methods
  • JShell Classes
  • JShell Commands
  • Exceptional Handling in JShell
Introduction
Read–Eval–Print Loop (REPL)  or language shell is a simple , interactive environment to execute code snippets and was there in scripting languages like python or Node. REPL is introduced as jshell in Java 9.

Pre Java 9 , just to print classic "Hello, World" statement , we have been following below steps :
1. Create a project
2. Create a class with main method and a print statement with "Hello, World"
3. Compile above class
4. Run this class

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World");
    }

}
Too many statements for a simple task!!

With jshell println method can be executed instantly! That's a bliss when you are new to java.
Further you don't need to recompile class whenever you introduce any changes. Jshell handles it
smoothly for you.

Running JShell
JShell is present as an executable in JDK9. Just move to bin directory of jdk9 installation and execute jshell command to run jshell. You will get a welcome message from jshell.

JShell Default Imports

By default shell imports following packages.You can import other packages by import command.
jshell> /imports
|    import java.util.*
|    import java.io.*
|    import java.math.*
|    import java.net.*
|    import java.util.concurrent.*
|    import java.util.prefs.*
|    import java.util.regex.*

JShell configurations
Default jshell configurations are adequate when you start learning this tool. But sometimes you need more control over and above default configurations .

Following configuration can be used to fine tune jshell.
1. Setting modules options
2. Setting classpath JARS
3. Feedback mode
4. JShell scripts
     a. Loading scripts
     b. Start-up scripts

Adding Modules

Executing commnad -add-modules and -module-path loads external classes from java modules.
Once you add modules you can import packages present in an added module.

jshell --add-modules jdk.httpserver


Adding JARS

External code can be accessed by jshell tool by setting classpath.Classpath can be set through following command :
jshell --class-path junit-4.12.jar


jshell --class-path junit-4.12.jar
 |  Welcome to JShell -- Version 9
 |  For an introduction type: /help intro
 jshell>  import org.junit.Testimport java.util.*

Feedback Modes

External To manage user interactions configuration , feedback mode can be used.
There four built-in feedback modes, in descending order of verbosity:
verbose, normal, concise, and silent.

jshell --feedback verbose


JShell Scripts

A JShell script is a sequence of JShell commands in a file , one for each line.
JShell script can be created externally in any editor or can be generated with any of the follwiing commnads.
jshell> /save aScript.jsh

jshell> /save -history historyScript.jsh

jshell> /save -start  startupScript.jsh
Name of script can be anything or anything like above or one of the predefined scripts given below.

DEFAULT - This script loads default behaviour and runs if one of script is not set
JAVASE - It imports all JAVA SE packages by default
PRINTING - defines JShell methods for print, println and printf in PrintStream

Loading JShell scripts
JShell scripts can be loaded by following command line on shell tool  :

     jshell aScript.jsh

or by opening script with /open command:
jshell> /open PRINTING
Start-up scripts

Running command -startup with predefined scripts or with user created scripts will load scripts at start up.

       jshell --startup PRINTING
       jshell --startup aScript.jsh


 JShell Expressions

In JShell you can fire any valid expression on a valid java type. JShell will evaluate that expression , assign it's result to a jshell variable.

Expressions that can be expressed in java , can also be executed on jshell command line tool.



 JShell Variables

Just like in class , you can declare a variable and it's type on jshell. Once declared you can access it , and modify to some other value.
It's possible to define a variable as private , static and final, but since everything runs in a single scope , it has no effect on declared variable.
Jshell issues a warning when you declare a variable as either static or final.



NOTE : Since final variables are not final , we can resassign it to some other value.


We can redefine variable on jshell tool and can assign it to some other type.

 JShell Methods

You can create method in Jshell command tool just like we define static method in a class. We also don't need to use static keyword for creating a method.


You can replace an existing method with a new method by changing it signature.







 JShell Classes

 Just like methods you can create a complete class on JShell tool.


Just like we redefined a method, on jshell tool you can also redefine a class.
Note : Redefining a class will automatically assign all variables of that type to null for safety reasons.


You can access any class in Jshell like you do on JVM.


If a class is present in any imported package, then you can use it there itself, else you can use import flag present on jshell.


If you wish to import everything that's provided in JAVA SE , you can run JAVASE startup script as mentioned earlier.

JShell Commands
Jshell has provided several useful commands for displaying information.

To display information following commands are used :
/vars : current variables
/methods : methods
/list : all entered snippets
/imports :  all imported packages
/help : for all available commands


Command : /vars


Exception Handling

Whenever an exception is throw on jshell , it prints the stack trace and also shows line number exactly like java.
It also reveals the line number where exception is thrown.

# Here exception is throw at line number 1.
Conclusion

JShell is extremely useful for testing java code snippets. A feature like this was missing in JAVA since very long and with it's introduction in JAVA 9, makes java stands on par with other modern languages.
Testing a snippet now with jshell is faster and it was needed for making development faster with shorter feedback cycle.


Happy Learning !!!







No comments:

Post a Comment