When I had started with Scala the first thing that I loved was the Scala REPL(read–eval–print loop). It’s a great tool to learn Scala and test code snippets.
While back in the java world we had to write a class with main method to try something. But with Java 9 release this will change. JShell will be our shiny new java REPL - http://openjdk.java.net/jeps/222 .
To get started with java 9 currently you can download and install the early access version from here - https://jdk9.java.net/download/.
Starting the REPL
Jshell is part of the jdk bin directory so if u have that in your path you can just run the jshell command to start the REPL.
There is a verbose mode which is feel will be very helpful for beginners. To start in verbose mode you can run : jshell –v.
To enter or exit verbose mode once you are in the repl you can use – /set feedback verbose and /set feedback normal.
The verbose mode will be a good way to learn java.
You can write any valid java expression and jshell will execute it and assign it to a variable.
Variables can be defined just like they are defined in a java program. Once a variable is defined it is present in the scope.
Did u notice no semicolons!
Jshell provides some helpful commands for you to get more information. Type /help and you will know all the list of commands. Here I have it for you to browse -
Jshell is not just for testing local code snippets. It gives you networking access which opens all sorts of possibilities.
One of my favourite things about jshell is it wraps checked exceptions in the background.
Here I read and print a file without catching IOEXception.
Another good thing is you dont have to worry about defining your methods and variables in correct order. The forward reference support is pretty good.
Pressing shift tab will get you the javadoc
The repl is definitely something which I think people will find useful.
Some features I would love to see:
- Paste Mode: to copy multiline commands
- Syntax Highlighting: Who doesn’t want that
- Multiline editing.
Having said that, I really like jshell. The tab auto-completion is quite good and features like forward reference & exception handling really make it usable. The ability to open external editor using /edit is cool.
It’s time to get rid of that TestMain.java class we all have in our workspace.