• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Java JShell – The Java Shell (Read-Eval-Print Loop) – REPL – JEP 222

August 28, 2018 by javainterviewpoint Leave a Comment

JShell is the Java’s new Command Line Tool – REPL, which allows you to execute Java code and get immediate result. JShell is Java’s first REPL tool [Read-Evaluate-Print-Loop] which evaluates declarations, statements, and expressions which are entered and immediately shows the results.

What is the use of Java JShell?

Usually in Java world during development we will be

• Writing the complete code
• Compile it and fix any errors which has occurred
• Run the code , find and fix the missing pieces
• Repeat the above process until the code works properly

Jshell helps you to try the different options in the code while developing your program, We can test individual statements, complex statements, methods, APIs with the JShell.

JShell cannot replace an IDE, it just act as a try out editor during code development.

How to Start JShell ?

JShell is bundled along with Java 9, To start JShell open a command prompt and enter the command jshell.

C:\Users\jip>jshell
| Welcome to JShell -- Version 9
| For an introduction type: /help intro

Make sure the JDK 9 is installed in your machine and jdk-9 is added to JAVA_HOME and jdk-9/bin to PATH variable.

Once the JDK is installed and the path is set correctly run the command java –version, it should be pointing to JDK 9.

C:\Users\jip>java -version
openjdk version "9"
OpenJDK Runtime Environment (build 9+181)
OpenJDK 64-Bit Server VM (build 9+181, mixed mode)

Alternatively you can open JShell directly by, In the command prompt browse the JDK 9 installation directory and get into the /bin folder and run the jshell.exe executable.

Say for example if Java installed in “C:\Program Files\Java\jdk-9”, cd into the \bin folder and run jshell.exe

How to Exit JShell ?

In order to exit from the JShell all you need to do is run the command /exit , you will be out of JShell.

JShell Hello World

Let’s write our first Hello World! Program using JShell, type the below code and hit enter

System.out.println(“Hello World!”)

That’s all, we ran our first Hello World program using JShell. We don’t need to create a class and define a main method and print the Hello World inside the main method. Just type print statement, JShell gives you the result immediately.

Variables and JShell Internal Variables

Defining a variable in JShell is similar to that of how you define programmatically. The only difference is that you don’t need to write the class and method here.

jshell> int a = 25
a ==> 25

Just type the variable to get the value assigned to the variable

jshell> a
a ==> 25

When you are evaluating an expression, JShell assigns the results to a JShell internal variable which will be prefixed with $, Let’s look into the below snippet

jshell> 10+20
$3 ==> 30

You can also refer the internal variable in the manipulation until the session is killed.

jshell> $3+10
$4 ==> 40

Once the internal variable is created, the type of internal variable cannot be changed. If we try to assign a decimal value to $3 we will get incompatible types error

jshell> $3 = 12.2
| Error:
| incompatible types: possible lossy conversion from double to int
| $3 = 12.2
|      ^--^

We can even concatenate two String like below

jshell> "Hello" + "World"
$5 ==> "HelloWorld"

You can test toUpperCase() method on the string like this

jshell> $5.toUpperCase()
$6 ==> "HELLOWORLD"

JShell Methods

We can define the methods in JShell the same way we define in the Classes.

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

Once the method is created, the method will be available until we quit the session

jshell> multiply(2,3)
$7 ==> 6

JShell Creation of Classes and Objects

In JShell, we are not limited to create statement, functions and variables. We can also create class and create object for the class just like a normal java program.

Lets create Multiply class

jshell> class Multiply {
...> private int a;
...> private int b;
...> Multiply () { }
...> Multiply (int a, int b) {
...> this.a = a;
...> this.b = b;
...> }
...> int multiply (int a, int b) {
...> return a * b;
...> }
...> }
| created class Multiply

We can create an object for the Multiply class and call the multiply() method.

jshell> Multiply m = new Multiply ();
m ==> [email protected]
jshell> m.multiply (2,3)
$7 ==> 6

JShell Commands

Lets take a look at some of the Jshell commands

/list – Displays the list of code snippets typed

This command lists the source code which we have typed

jshell> /list

1 : int a = 25;
2 : a
3 : 10+20
4 : $3+10
5 : "Hello" + "World"
6 : $5.toUpperCase()
7 : int multiply (int a, int b)
{
return a * b;
}
8 : multiply ( 2, 3)

/vars – Displays the list of all the variables

This command lists the varaibles which we have used in the current JShell session.

jshell> /vars
| int a = 25
| int $3 = 30
| int $4 = 40
| String $5 = "HelloWorld"
| String $6 = "HELLOWORLD"
| int $8 = 6

/methods

This command displays the list of methods which we have created in the particular session

jshell> /methods
|    int multiply(int,int)

/history – View History

This command displays the complete history of the jshell session

jshell> /history

int multiply(int a, int b)
{
return a * b;
}
/methods
/history

/save – Saving a snippet to the file

Saves snippet source to a file.

jshell> /save E:\JIP\jshell.txt

For example, The above code creates a new jshell.txt under the specified path, with the below content

int multiply(int a, int b)
{
return a * b;
}

/edit – Editing the code in an External Editor

This launches the Jshell edit pad where you can edit the code snippet and save it

Java JShell Edit 1

When you have multiple snippets then you specify the snippet number, after the edit command to edit the particular snippet

eg : /edit 2

Java JShell Edit 2

/drop – Dropping a Snippet

You can drop a particular snippet you have typed by using the command /drop <id>.

jshell> /list

   1 : int multiply (int a, int b)
       {
       return a * b;
       }
   2 : int add (int a, int b)
       {
       return a+b;
       }

jshell> /drop 2
|  dropped method add(int,int)

jshell> /list

   1 : int multiply (int a, int b)
       {
       return a * b;
       }

Tab Completion

This is an interesting feature of JShell, while entering the code you can hit Tab key to autocomplete the remaining or show the list of possibilities. It can even the show the documentation if any

For example, we have method called multiply(), while entering mu just press the Tab key Jshell will automatically completes it for you.

jshell> /methods
|    int multiply(int,int)

jshell> mul <Press Tab Key>
multiply(

jshell> multiply(
multiply(

Signatures:
int multiply(int a, int b)

<press tab again to see documentation>

jshell> multiply(
int multiply(int a, int b)
<no documentation found>

<press tab again to see all possible completions; total possible completions: 540>

Filed Under: Core Java, Java Tagged With: Java JShell, JEP 222, JShell, Read-Eval-Print Loop, REPL

Leave a Reply Cancel 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.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·