JShell, which has been introduced since Java 9, is an interactively evaluates declarations, statements, and expressions of the Java programming language in a read-eval-print loop (REPL). This tutorial is going to show how to execute and exit a script with JShell.

To learn more about JShell commands, please visit Java 9 JShell Cheat Sheet.

1. Execute A Script With JShell

To execute a script with JShell, we can use the following syntax:

For example, let’s see a simple script /opt/HelloJShellScript.java with the content as follows:

To run the script with JShell:

Let’s see the output of the script:

Execute A Script With JShell

Execute A Script With JShell

2. Exit JShell After Executing A Script

If we run a script with JShell and we don’t exit the JShell, then the JShell session still remains to open. For example, let’s see another simple JShell script /opt/jshell-script-example.java with the following content:

Let’s execute the script with JShell:

Let’s see the output of the script:

Exit JShell After Executing A Script

Exit JShell After Executing A Script – The JShell session still remains opening

We can see that the JShell still remains opening. To exit JShell after executing a script, we can put a the /exit command at the end of the script. For example, let’s modify the above JShell script and put the /exit command at the end of the script.

And then execute the JShell script again and observe the output:

Exit JShell After Executing A Script - Close JShell session

Exit JShell After Executing A Script – Close JShell session

We can see that the JShell session now is closed.

3. Conclusion

The tutorial has illustrated us how to execute a script with JShell and how to exit JShell after executing a script as well. We can see that both of them are pretty simple. To run a script with JShell, we simply need to put the path to the script at the first parameter of the JShell command while to exit JShell after executing, we just need to put the /exit command at the end of the script.

Below are other Java 9 related tutorials for your references:

How To Import The External Library Into Java 9 Shell

Java 9 – New Methods Of The Optional Class

Streams API Updates In Java 9

How To Compare Arrays In Java 9

Java 9 HTTP/2 Client API Example

Java 9 – Effectively Final Variables In try-with-resources

 

 

0 0 vote
Article Rating