JShell – Java 9 interpreter (REPL) – Getting Started with Examples and Video Tutorial

Why JShell – Java 9 interpreter (REPL)?

In order to evaluate your statements instantly without creating a project and compiling whole source code, Oracle recently introduced JShell in Java 9. JShell is a similar tool like other compiled language own for statements interpretation, sometimes called REPL (read-eval-print loop). It helps programmer to quickly evaluate code snippets without compiling the whole code.

What is REPL?

A read-eval-print loop (REPL) is known as an interactive or language shell that takes single user inputs, evaluates them and return the result to user. A program written in REPL environment is executed piece wise or in steps. Such interfaces are similar to the classic Lisp machine interactive environment.

How JShell works?

A simple programming environment in the command line that reads user’s input, evaluates it, prints the result, and then repeats the same cycle.  You can write Java language expressions and statements in the JShell, and they will be evaluated on their own without having to wrap them in classes or methods.

It works similar to Scala or Python interpreter or other JVM languages that have a REPL like Kotlin and Groovy.

How to Run JShell?

Once you downloaded and installed jdk9 (download from here), you may locate java installation path and find the jshell executable in bin directory. Type jshell in your terminal to start JShell session. It is suggested to use verbose mode for the first time.

|  Welcome to JShell -- Version 9
|  For an introduction type: /help intro

jshell>

If jshell command is not recognizable by your terminal. Set JAVA_HOME path  and make sure JAVA_HOME/bin is added to the PATH variable.

If it works fine, write the first Hello World example using JShell (REPL) environment.

jshell> System.out.println("Hello World");
Hello World

Default Imports

Variables and Expressions

JShell allows you to declare valid java variables and expressions, and it will tell you the returned value, it’s type and assign it to a variable and result

jshell> int a = 20
a ==> 20

jshell> int b = 30
b ==> 30

jshell> int c = a*b
c ==> 600

Creating java valid string variable and concatenating them. Find the example below

jshell> String str = "Hello"
str ==> "Hello"

jshell> String str2 = "World"
str2 ==> "World"

jshell> String concat = str + " " + str2
concat ==> "Hello World"

Methods

You can define methods and can redefine them with new functionality.

jshell> void sayhello(){System.out.println("Hello JShell");}
|  created method sayhello()

jshell> sayhello()
Hello JShell

jshell> void sayhello(){System.out.println("Hello World, Its JShell Environment");}
|  created method sayhello()

jshell> sayhello()
Hello World, Its JShell Environment

You can define return type, parameters and selection statements as given in the example below.

jshell> String grade(int marks){
   ...> if(marks>60){
   ...> return "Pass";}
   ...> else{
   ...> return "Fail";}
   ...> }
|  created method grade(int)

jshell> grade(70)
$12 ==> "Pass"

jshell> grade(50)
$13 ==> "Fail"

Class

Creating a class, class methods and creating objects and invoking method in JShell environment.

jshell> class Student{
   ...> int Id;
   ...> Student(int id){
   ...> Id=id;
   ...> }
   ...> int getID(){
   ...> return Id;
   ...> }
   ...> }
|  created class Student


jshell> Student s = new Student(1001)
s ==> Student@5e853265

jshell> s.getID()
$25 ==> 1001

jshell> new Student(1002)
$26 ==> Student@5d76b067

jshell> $26.getID()
$27 ==> 1002

Commands

Aparat from language syntax you can execute jshell commands. Some of the most useful ones (/help to list all of them) are:
Default Imports

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.*

Listing Variables

jshell> /var
|    int a = 20
|    int b = 30
|    int c = 600
|    String str = "Hello"
|    String str2 = "World"
|    String concat = "Hello World"
|    String $12 = "Pass"
|    String $13 = "Fail"
|    Student $15 = Student@4b952a2d
|    int $17 = 1002
|    Employee e = Employee@30b8a058
|    int $22 = 0
|    Student s = Student@5e853265
|    int $25 = 1001
|    Student $26 = Student@5d76b067
|    int $27 = 1002

Listing Methods

jshell> /method
|    void sayhello()
|    String grade(int)

List Classes

jshell> /type
|    class Employee
|    class Student

Save source code in a file
You can save all the source that you have typed in the current JShell session in a file using /save command

jshell> /save test.txt

You can open all the source code that you have previously typed and saved in a text file.

jshell> /open test.txt

You can also open a java file in a similar way

jshell> /open test.java

Listing History

jshell> /history

int a = 20
int b = 30
c=a*b
int c = a*b
String str = "Hello"
String str2 = "World"
String concat = str + " " + str1
String concat = str + " " + str2
void sayhello(){System.out.println("Hello JShell");}
sayhello()
void sayhello(){system.out.println("Hello World, Its JShell Environment");}
void sayhello(){System.out.println("Hello World, Its JShell Environment");}
sayhello()
String grade(int marks){
if(marks>60){
return "Pass";}
else{
return "Fail";}
}
grade(70)
grade(50)
class Student{
int ID;
Student(int id){
ID=id;
}
int getId(){
return ID;
}
}
new Student(1001)
Student s = new Student(1002)
s.getId()
class Student{
int id;
Student(){}
Student(int id){
id =id;
}
int getId(){}
int getId(){}
int getId(){ return id; }
}
class Student{
Student(){}
Student(int id){
id =id;
}
int getId(){ return id; }
}
Student s = new Student(1001);
class Employee{
int empID;
Employee(int empID){
empID= empID;
}
int getEmpID(){
return empID;
}
}
Employee e = new Employee(1101);
c.getEmpID()
e.getEmpID()
class Student{
int Id;
Student(int id){
Id=id;
}
int getID(){
return Id;
}
}
Student s = new Student(1001)
s.getID()
new Student(1002)
$26.getID()
/import
/var
/method
/class
/history

Edit Method Class or any piece of Code
Running edit command will open your code in a editor.

jshell> /edit Student
|  replaced class Student

jshell> new Student(10000,"AAAA")
$29 ==> Student@1f554b06

jshell> $29.getName()
$30 ==> "AAAA"

jshell> $29.getID()
$31 ==> 10000

Tab Option
You can press tab, to check which methods you can call.

jshell> Student s = new Student(1000,"AAAAAA")
s ==> Name of Student is AAAAAA and ID number 1000

jshell> s
s            sayhello()   short        str          str2         sun

Signatures:
s:Student

Now, for checking what methods are available for use for the above Student object, type s followed by a dot (.), and then press tab

jshell> s.
Id            equals(       getClass()    getID()       getName()     hashCode()    notify()      notifyAll()   sName         toString()    wait(

jshell> s.getName()
$35 ==> "AAAAAA"

Forward References

JShell supports forward references. Which means you can define functions that refer to other methods or variables that will be defined at a later stage. But you can’t invoke it until reference method is not defined.

jshell> void calculate(int v1, int v2){
   ...> multiply(v1,v2);
   ...> }
|  created method calculate(int,int), however, it cannot be invoked until method multiply(int,int) is declared

jshell> int multiply(int v1, int v2){
   ...> return v1*v2;
   ...> }
|  created method multiply(int,int)

jshell> /edit calculate
|  modified method calculate(int,int)

jshell> calculate(10,20)
200

Collections

jshell> List vals = List.of("A","B","C")
vals ==> [A, B, C]

jshell> vals.forEach(v->System.out.println(v))
A
B
C

Streams

jshell> Stream myStream = Stream.of(1, 2, 3, 4, 5)
myStream ==> java.util.stream.ReferencePipeline$Head@e720b71

jshell> myStream.map(number -> number * number).
   ...> filter(number -> number % 2 == 0).
   ...> forEach(System.out::println)
4
16

Video Tutorial

Above mentioned example are recorded in video given below:

Conclusion

JShell is a very useful tool for prototyping and testing Java code snippets. It will help beginners to learn and adopt java language quickly. It will help developers to quickly evaluate code, without writing classes, methods and imports. I highly recommend checking it out. There is also a JShell Java api which allows you to evaluate JShell from java.

Leave a Reply

Your email address will not be published. Required fields are marked *

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