Java 9 – The Java Shell (RPEL) Part 1 | Code Factory


Index Page : Link

Donate : Link

Medium Blog : Link

Applications : Link

1. Introduction to the JShell

Jshell is also known as interactive console.

JShell is Java’s own REPL Tool.

REPL means -> Read, Evaluate, Print and Loop

By using this tool we can execute Java code snippets and we can get immediate results. For beginners it is very good to start programming in fun way.

By using this Jshell we can test and execute Java expressions, statements, methods, classes etc. It is useful for testing small code snippets very quickly, which can be plugged into our main coding based on our requirement.

Prior to Java 9 we cannot execute a single statement, expression, methods without full pledged classes. But in Java 9 with JShell we can execute any small piece of code without having complete class structure.

It is not new thing in Java. It is already there in other languages like Python, Swift, Lisp, Scala, Ruby etc..

Python -> IDLE
Apple’s Swift Programming Language -> PlayGround

Limitations of JShell:

  1. JShell is not meant for Main Coding. We can use just to test small coding snippets, which can be used in our Main Coding.
  2. JShell is not replacement of Regular Java IDEs like Eclpise, NetBeans etc

2. Getting Started with JShell

Starting and Stopping JShell:

Open the jshell from the command prompt in verbose mode

jshell -v

R:\CodeFactory>jshell -v
|  Welcome to JShell -- Version 11.0.10
|  For an introduction type: /help intro

How to exit jshell:

jshell> /exit
|  Goodbye

Note: Observe the difference b/w with -v and without -v (verbose mode)

R:\CodeFactory>jshell
|  Welcome to JShell -- Version 11.0.10
|  For an introduction type: /help intro

jshell> 1+2
$1 ==> 3



R:\CodeFactory>jshell -v
|  Welcome to JShell -- Version 11.0.10
|  For an introduction type: /help intro

jshell> 1+2
$1 ==> 3
|  created scratch variable $1 : int

Note: If any information displaying on the jshell starts with ‘|’, it is the information to the programmer from the jshell

jshell> 1+2
$1 ==> 3
|  created scratch variable $1 : int

jshell> 1+2-3*4/5
$2 ==> 1
|  created scratch variable $2 : int

jshell> System.out.println("CodeFactory")
CodeFactory

Here if we observe the output not starts with | because it is not information from the Jshell.

Note: Terminating semicolons are automatically added to the end of complete snippet by JShell if not entered. .

jshell> Math.sqrt(2)
$4 ==> 1.4142135623730951
|  created scratch variable $4 : double

jshell> Math.max(1,2)
$5 ==> 2
|  created scratch variable $5 : int

jshell> Math.random()
$6 ==> 0.5444657864956806
|  created scratch variable $6 : double

Note: We are not required to import Java.lang package, because by default available.

Note: The following packages are bydefault available to the Jshell and we are not required to import. We can check with /imports command

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.*
jshell> ArrayList<String> l = new ArrayList<>()
l ==> []
|  created variable l : ArrayList<String>

jshell> l.add("Code");l.add("Factory")
$8 ==> true
|  created scratch variable $8 : boolean
$9 ==> true
|  created scratch variable $9 : boolean

jshell> l
l ==> [Code, Factory]
|  value of l : ArrayList<String>

jshell> l.isEmpty()
$11 ==> false
|  created scratch variable $11 : boolean

jshell> l.get(1)
$12 ==> "Factory"
|  created scratch variable $12 : String

jshell> l.get(2)
|  Exception java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 2
|        at Preconditions.outOfBounds (Preconditions.java:64)
|        at Preconditions.outOfBoundsCheckIndex (Preconditions.java:70)
|        at Preconditions.checkIndex (Preconditions.java:248)
|        at Objects.checkIndex (Objects.java:372)
|        at ArrayList.get (ArrayList.java:459)
|        at (#13:1)

jshell> l.size()
$14 ==> 2
|  created scratch variable $14 : int

jshell> l.isEmpty()? "Empty":"Not empty"
$15 ==> "Not empty"
|  created scratch variable $15 : String

jshell> for(int i=0;i<5;i++)System.out.println(i
)
0
1
2
3
4

Note: Interlly jshell having Java compiler which is responsible to check syntax. If any violation we will get Compile time error which is exactly same as normal compile time errors.

jshell> System.out.println(a+b)
|  Error:
|  cannot find symbol
|    symbol:   variable a
|  System.out.println(a+b)
|                     ^
|  Error:
|  cannot find symbol
|    symbol:   variable b
|  System.out.println(a+b)
|                       ^

jshell> system.out.println()
|  Error:
|  package system does not exist
|  system.out.println()
|  ^--------^

Note: In our program if there is any chance of getting checked exceptions then compulsory we required
to handle either by try-catch or by throws keyword. Otherwise we will get Compile time error.
But in the case of Jshell, jshell itself will takes care of these and we are not required to use trycatch or throws. Thanks to Jshell.

jshell> PrintWriter pw = new PrintWriter("abc.txt");pw.println("CodeFactory");pw.flush();
pw ==> java.io.PrintWriter@55d56113
|  created variable pw : PrintWriter

3. Getting Help from the JShell

JShell can provide complete information about available commands with full documentation, and how to use each command and what are various options are available etc..

1) To know list of options allowed with jshell

Type jshell –help from normal command prompt

R:\CodeFactory>jshell --help
Usage:   jshell <option>... <load-file>...
where possible options include:
    --class-path <path>   Specify where to find user class files
    --module-path <path>  Specify where to find application modules
    --add-modules <module>(,<module>)*
                          Specify modules to resolve, or all modules on the
                            module path if <module> is ALL-MODULE-PATHs
    --enable-preview      Allow code to depend on preview features of this release
    --startup <file>      One run replacement for the startup definitions
    --no-startup          Do not run the startup definitions
    --feedback <mode>     Specify the initial feedback mode. The mode may be
                            predefined (silent, concise, normal, or verbose) or
                            previously user-defined
    -q                    Quiet feedback.  Same as: --feedback concise
    -s                    Really quiet feedback.  Same as: --feedback silent
    -v                    Verbose feedback.  Same as: --feedback verbose
    -J<flag>              Pass <flag> directly to the runtime system.
                            Use one -J for each runtime flag or flag argument
    -R<flag>              Pass <flag> to the remote runtime system.
                            Use one -R for each remote flag or flag argument
    -C<flag>              Pass <flag> to the compiler.
                            Use one -C for each compiler flag or flag argument
    --version             Print version information and exit
    --show-version        Print version information and continue
    --help, -?, -h        Print this synopsis of standard options and exit
    --help-extra, -X      Print help on non-standard options and exit

2) To know the version of jshell

Type jshell –version from normal command prompt

R:\CodeFactory>jshell --version
jshell 11.0.10

3) To know introduction of jshell

jshell> /help intro
|
|                                   intro
|                                   =====
|
|  The jshell tool allows you to execute Java code, getting immediate results.
|  You can enter a Java definition (variable, method, class, etc), like:  int x = 8
|  or a Java expression, like:  x + x
|  or a Java statement or import.
|  These little chunks of Java code are called 'snippets'.
|
|  There are also the jshell tool commands that allow you to understand and
|  control what you are doing, like:  /list
|
|  For a list of commands: /help

4) For List of commands

jshell> /help
|  Type a Java language expression, statement, or declaration.
|  Or type one of the following commands:
|  /list [<name or id>|-all|-start]
|       list the source you have typed
|  /edit <name or id>
|       edit a source entry
|  /drop <name or id>
|       delete a source entry
|  /save [-all|-history|-start] <file>
|       Save snippet source to a file
|  /open <file>
|       open a file as source input
|  /vars [<name or id>|-all|-start]
|       list the declared variables and their values
|  /methods [<name or id>|-all|-start]
|       list the declared methods and their signatures
|  /types [<name or id>|-all|-start]
|       list the type declarations
|  /imports
|       list the imported items
|  /exit [<integer-expression-snippet>]
|       exit the jshell tool
|  /env [-class-path <path>] [-module-path <path>] [-add-modules <modules>] ...
|       view or change the evaluation context
|  /reset [-class-path <path>] [-module-path <path>] [-add-modules <modules>]...
|       reset the jshell tool
|  /reload [-restore] [-quiet] [-class-path <path>] [-module-path <path>]...
|       reset and replay relevant history -- current or previous (-restore)
|  /history [-all]
|       history of what you have typed
|  /help [<command>|<subject>]
|       get information about using the jshell tool
|  /set editor|start|feedback|mode|prompt|truncation|format ...
|       set configuration information
|  /? [<command>|<subject>]
|       get information about using the jshell tool
|  /!
|       rerun last snippet -- see /help rerun
|  /<id>
|       rerun snippets by ID or ID range -- see /help rerun
|  /-<n>
|       rerun n-th previous snippet -- see /help rerun
|
|  For more information type '/help' followed by the name of a
|  command or a subject.
|  For example '/help /list' or '/help intro'.
|
|  Subjects:
|
|  intro
|       an introduction to the jshell tool
|  keys
|       a description of readline-like input editing
|  id
|       a description of snippet IDs and how use them
|  shortcuts
|       a description of keystrokes for snippet and command completion,
|       information access, and automatic code generation
|  context
|       a description of the evaluation context options for /env /reload and /reset
|  rerun
|       a description of ways to re-evaluate previously entered snippets

5) To get information about a particular command

jshell>/help commandname

jshell> /help list
|
|                                   /list
|                                   =====
|
|  Show the snippets, prefaced with their snippet IDs.
|
|  /list
|       List the currently active snippets of code that you typed or read with /open
|
|  /list -start
|       List the evaluated startup snippets
|
|  /list -all
|       List all snippets including failed, overwritten, dropped, and startup
|
|  /list <name>
|       List snippets with the specified name (preference for active snippets)
|
|  /list <id>
|       List the snippet with the specified snippet ID.
|       One or more IDs or ID ranges may used, see '/help id'

To get Information about methods command

jshell> /help methods
|
|                                  /methods
|                                  ========
|
|  List the name, parameter types, and return type of methods that were entered.
|
|  /methods
|       List the name, parameter types, and return type of the current active methods
|
|  /methods <name>
|       List methods with the specified name (preference for active methods)
|
|  /methods <id>
|       List the method with the specified snippet ID.
|       One or more IDs or ID ranges may used, see '/help id'
|
|  /methods -start
|       List the methods in the evaluated startup snippets
|
|  /methods -all
|       List all snippets including failed, overwritten, dropped, and startup

6) To get just names of all commands without any description

just type / followed by tab

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

<press tab again to see synopsis>

If we press tab again then we will get one line synopsis for every command:

jshell> /
/!
rerun last snippet -- see /help rerun

/-<n>
rerun n-th previous snippet -- see /help rerun

/<id>
rerun snippets by ID or ID range -- see /help rerun

/?
get information about using the jshell tool

/drop
delete a source entry

/edit
edit a source entry

/env
view or change the evaluation context

/exit
exit the jshell tool

/help
get information about using the jshell tool

/history
history of what you have typed

/imports
list the imported items

/list
list the source you have typed

/methods
list the declared methods and their signatures

/open
open a file as source input

/reload
reset and replay relevant history -- current or previous (-restore)

/reset
reset the jshell tool

/save
Save snippet source to a file

/set
set configuration information

/types
list the type declarations

/vars
list the declared variables and their values

<press tab again to see full documentation>

If we press tab again then we can see full documentation of command one by one:

jshell> /
/!
Reevaluate the most recently entered snippet.

<press tab to see next command>
jshell> /
/-<n>
Reevaluate the n-th most recently entered snippet.

<press tab to see next command>
jshell> /
/<id>
/<id> <id> <id>

/<id>-<id>

Reevaluate the snippets specified by the ID or ID range.
An ID range is represented as a two IDs separated by a hyphen, e.g.:  3-17
Startup and error snippets maybe used, e.g.:  s3-s9    or   e1-e4
Any number of IDs or ID ranges may be used, e.g.:  /3-7 s4 14-16 e2
See '/help id'.

<press tab to see next command>

7) To know the list of options available for a command

jshell>/command – tab

jshell> /list -
-all       -history   -start

<press tab again to see synopsis>
jshell> /list -

If we press tab again then we will get synopsis:

jshell> /list -
list the source you have typed

<press tab again to see full documentation>
jshell> /list -

If we press tab again then we will get documentation:

jshell> /list -
Show the snippets, prefaced with their snippet IDs.

/list
        List the currently active snippets of code that you typed or read with /open

/list -start
        List the evaluated startup snippets

/list -all
        List all snippets including failed, overwritten, dropped, and startup

/list <name>
        List snippets with the specified name (preference for active snippets)

/list <id>
        List the snippet with the specified snippet ID.
        One or more IDs or ID ranges may used, see '/help id'

4. Understanding JShell Snippets

What are Coding Snippets?

Everything what allowed in Java is a snippet. It can be
Expression,Declaration,Statement,classe,interface,method,variable,import,…
We can use all these as snippets from jshell.

***But package declarations are not allowed from the jshell.

jshell> System.out.println("Code Factory")
Code Factory

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

jshell> 10+20
$3 ==> 30
|  created scratch variable $3 : int

jshell> $3<x
$4 ==> false
|  created scratch variable $4 : boolean

jshell> String s=5
|  Error:
|  incompatible types: int cannot be converted to java.lang.String
|  String s=5;
|           ^

jshell> String s="CodeFactory"
s ==> "CodeFactory"
|  created variable s : String

jshell> public void m1()
   ...> {
   ...> System.out.println("Code Factory");
   ...> }
|  created method m1()

jshell> m1()
Code Factory

Note: We can use /list command to list out all snippets stored in the jshell memory with snippet id.

jshell> /list

   1 : System.out.println("Code Factory")
   2 : int x=10;
   3 : 10+20
   4 : $3<x
   5 : String s="CodeFactory";
   6 : public void m1()
       {
       System.out.println("Code Factory");
       }
   7 : m1()

The numbers 1,2,3 are snippet id. In the future we can access the snippet with id directly.

Note: There are some snippets which will be executed automatically at the time jshell startup, and these are called start-up snippets. We can also add our own snippets as start-up snippets.

We can list out all start-up snippets with command: /list -start

jshell> /list -start

  s1 : import java.io.*;
  s2 : import java.math.*;
  s3 : import java.net.*;
  s4 : import java.nio.file.*;
  s5 : import java.util.*;
  s6 : import java.util.concurrent.*;
  s7 : import java.util.function.*;
  s8 : import java.util.prefs.*;
  s9 : import java.util.regex.*;
 s10 : import java.util.stream.*;

All these are default imports to the jshell.

We can list out all snippets by the command: /list -all

jshell> /list -all

  s1 : import java.io.*;
  s2 : import java.math.*;
  s3 : import java.net.*;
  s4 : import java.nio.file.*;
  s5 : import java.util.*;
  s6 : import java.util.concurrent.*;
  s7 : import java.util.function.*;
  s8 : import java.util.prefs.*;
  s9 : import java.util.regex.*;
 s10 : import java.util.stream.*;
   1 : System.out.println("Code Factory")
   2 : int x=10;
   3 : 10+20
   4 : $3<x
  e1 : Strng s=5;
  e2 : String s=5;
   5 : String s="CodeFactory";
  e3 : public void m1()
       {
       System.out.println("Code Factory")
       }
   6 : public void m1()
       {
       System.out.println("Code Factory");
       }
   7 : m1()

We can access snippets by using id directly.

jshell> /list 3

   3 : 10+20

jshell> /list 3 4

   3 : 10+20
   4 : $3<x

jshell> /list 34
|  No snippet with ID: 34

We can also access snippets directly by using name. The name can be either variable name, class name, method name etc

jshell> /list m1

   6 : public void m1()
       {
       System.out.println("Code Factory");
       }

jshell> /list s

   5 : String s="CodeFactory";

We can execute snippet directly by using id with the command: /id

jshell> /3
10+20
$8 ==> 30
|  created scratch variable $8 : int

jshell> /7
m1()
Code Factory

We can use drop command to drop a snippet(Making it inactive)
We can drop snippet by name or id.

jshell> /list

   1 : System.out.println("Code Factory")
   2 : int x=10;
   3 : 10+20
   4 : $3<x
   5 : String s="CodeFactory";
   6 : public void m1()
       {
       System.out.println("Code Factory");
       }
   7 : m1()
   8 : 10+20
   9 : m1()

jshell> /drop $4
|  dropped variable $4

jshell> /list

   1 : System.out.println("Code Factory")
   2 : int x=10;
   3 : 10+20
   5 : String s="CodeFactory";
   6 : public void m1()
       {
       System.out.println("Code Factory");
       }
   7 : m1()
   8 : 10+20
   9 : m1()

Leave a comment