Java 9 Introduced Java Shell or JShell which is a Read-Evaluate-Print-Loop (REPL) tool which can be used for prototyping, debugging and learning Java, Java API interactively using a shell. This eliminates the dummy test classes needs to be written with a Java main method, compile it and run it. Let’s have a look at some of the use cases for this.
Getting Started
The JShell can be invoked by issue command jshell on a Unix, Linux, Mac or Windows terminal.
Which will open an interactive shell which can take in Java syntaxes and give outputs accordingly. Lets just define some variables by the names greeting and object.
Now we can concatenate those two and print to the screen.
Supports Tab Completion
After the start of the variable name pressing the tab key will complete the variable name.
jshell> gree
jshell> greeting
Pressing tab key twice will show the variable type and Java documentation if required by pressing tab key thrice.
Using Methods of Variables
Since greeting is a String variable we can use the methods available on it. These can also be accessed using the tab key.
jshell> greeting.to
toCharArray() toLowerCase( toString() toUpperCase(
Error Information
The REPL shell will show errors descriptively with the line no as below.
Imports
By default following imports are available in the JShell.
- java.io.*
- java.math.*
- java.net.*
- java.nio.file.*
- java.util.*
- java.util.concurrent.*
- java.util.function.*
- java.util.prefs.*
- java.util.regex.*
- java.util.stream.*
And you can have additional imports if you want. Example you can use java.util.Arrays class as below
Custom Methods
You can define your own custom methods and call them in the JShell as below:
Custom Classes
You can also define your own custom classes and use them in JShell as below:
Static methods can also be defined and can be called without instantiating the class.
Conclusion
This is a small summary of the capabilities of the JShell tool but it has much broader and advanced features which can be learned by going through the Oracle official documentation.
References
Java 10 JShell – https://www.techtalks.lk/blog/2018/9/java-10-jshell