Jshell is a command line interface to evaluate the java code snippets. Normally, it is called REPL(Read Evaluate Print Loop). Jshell came in Java9. Jshell gives you a place where you can experiment first if it works then use that code for your work. It is an extremely good tool for prototyping and for those who are especially new to Java.
The main thing that we all should know is Jshell can understand two types of commands. First, The commands which we write for evaluation(Java snippets code) and handled by JVM. Second, The commands to Jshell itself which always starts with a slash(/).
Let’s go for little practical stuff so, that we can have a better understanding of how it actually works.
To start Jshell you just need to type jshell on the terminal(for Linux) then immediately you will enter into Jshell where you can explore new libraries and do many more things.
To exit from Jshell you just need to type /exit or /ex(These commands are starting from slash(/) if you noticed here so these are the Jshell commands) and if you want an immediate exit from Jshell press (CTRL + D).
So, let’s start from the basics, where we will evaluate the result of (1 + 1) and you will get the immediate result for the same and that result will be assigned to an implicit variable, with the name starting with a $ symbol, which actually Jshell creates for you.
The cool thing about Jshell is that for the first time in java you can skip the semicolon part at the time of declaring single line statements. You can see the imports by typing /imports.
If you want to add any extra module or jar in the Jshell you can add that very easily with the below commands:
For Module(This command will work only when starting Jshell):
jshell -v --add-modules java.net.http
For Jar:
jshell> /env -class-path /opt/libs/commonslang33.4.jar:/opt/libs/guava-19.0.jar
There are many more commands which Jshell accepts, we will cover some interesting commands here and you can see all the commands by just typing /help on the Jshell terminal :
You can get information on the current variables, methods, and types with the /vars, /methods, and /types commands, respectively. You can get a list of entered snippets with the /list command.
Now, I would like to discuss one more feature of Jhsell(Only Jshell REPL provides this) which I really like and is helpful as well.
We will cover this feature by an example, suppose you declared one String and you want to apply a method on that string which is charAt() and you don’t know the signature of this method but you want to use this so, in this case, if you are using Jshell then just type String and then method name and after that just press the tab key it will give you the signature of that method.
And if you press tab again it will give you the documentation as well, isn’t it amazing?
I hope this blog was enjoyable, and you have gained a basic understanding of how to start working with Jshell.