Javatpoint Logo
Javatpoint Logo

Java Shell Tool (JShell)

It is an interactive Java Shell tool, it allows us to execute Java code from the shell and shows output immediately. JShell is a REPL (Read Evaluate Print Loop) tool and run from the command line.

Advantages of JShell

Jshell has reduced all the efforts that are required to run a Java program and test a business logic.

If we don't use Jshell, creating of Java program involves the following steps.

  • Open editor and write program
  • Save the program
  • Compile the program
  • Edit if any compile time error
  • Run the program
  • Edit if any runtime error
  • Repeat the process

Jshell does not require above steps. We can evaluate statements, methods and classes, even can write hello program without creating class.


How to Start JShell

To start Jshell, first we must have installed Java 9 then open terminal in Linux or command prompt in windows and type jshell ?v. It will start jshell session and displays a welcome message to the console.

Java 9 Shell Tool 1

Hello Java Message

To display a simple "Hello Java" message, write print command without creating class and hit enter.

Java 9 Shell Tool 2

Variables

We can declare variables and use anywhere throughout Jshell session. Let's create an integer variable.

Java 9 Shell Tool 3

Semicolon (;) is optional, we can leave it and it works fine. See, variable b is created without using semicolon.

Java 9 Shell Tool 4

Scratch Variables

If we don't provide variable name, Java create implicit variable to store the value. These variables start with $ sign. We can use these variable by specifying implicit variable, as we did in the in the following screen-shot.

Java 9 Shell Tool 5

Expressions

We can test any valid Java expression to get instant output. See, the following example.

Adding two integers

Compound expression


Methods

To test method business logic, create an method and get result immediately. See, the following example.

Calling method

To create class, write source code for the class and call its method by creating object immediately. See the following example.


Class


Package Imports

By default, 10 packages are imported and can also be imported any package by using import statement.

To see, default import packages, we can use following command.

Importing java.sql package.

Listing import packages and it will show available accessible packages.

Now number of packages are 11 including new one java.sql.*.


Jshell Commands

Jshell provides various useful commands that we can use to modify environment, manage code and to get code related information. Following are the useful information.

Package Imports

Command /vars to show variables.

To get all written source code, use /list


Next TopicModule System





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA