Introduce about JShell in Java

If you have ever worked with some languages like Python, Scala, you may know we can write code and execute code for those languages using only the command line. This will allow us to test some code without having to do a lot of things, simply writing code and executing. This function is also known as REPL, Read-Eval-Print-Loop. Grabbing that essential need, from version 9, Java introduced us to a similar tool called JShell. What is it? I will have some introduction about it in this tutorial.

To start JShell, just open Terminal and enter the following statement:

Introduce about JShell in Java

Let try writing an example with System.out.print().

Introduce about JShell in Java

You see, using JShell, we do not need to create new class, add main() method then run. All is simply what we want the program to do, eliminating redundant manipulation.

To find out what JShell can do for us, you can enter the command line “/ help”.

Introduce about JShell in Java

Here, you will find JShell can do a lot of things for us.

For example, the import command in Java that we often use, JShell supports us by importing some packages, and so when we use it, we do not need to declare those packages with the import statement anymore. To check the packages that JShell has imported, you can enter the following statement:

Introduce about JShell in Java

For example, normally, when using the Stream object in the IDE, we will write code like this:

In JShell is simply:

Introduce about JShell in Java

JShell also has good support for methods.

For example, I define a method sum() as follows:

Introduce about JShell in Java

Then, I can call to use the sum() method as follows:

Introduce about JShell in Java

You notice that after executing the code, if the result returns a value, JShell will automatically assign that value to a variable. As an example of our sum() method, after executing the code sum(2, 3), the return value is assigned to variable $3.

We can reuse these variables. For example, you can reprint the $3 variable as follows:

Introduce about JShell in Java

To exit JShell, just enter “/exit”.

Introduce about JShell in Java

Add Comment