jshell is a new-in-Java-9 tool - a REPL for Java!! I was not sure at first how useful it would be but since I started playing with it I've been finding more and more uses for it, and it's pretty cool. There's a couple of surprising things though. Lets have a look.

A quick look

and we’re at the REPL prompt. We can do a few totally unsurprising (but neat!) things:

There’s also a few meta commands, try starting with /help

The $n are references to the results:

etc. We can create, modify and replace classes on the fly:

Classes are created then modified or replaced when changed. If the change alters a method signature or adds/removes a field then the class is replaced , otherwise it is just modified . What happens to instances when you do that?

Modifying a class

Modifying a class alters existing instances:

Replacing a class

Replacing a class nullifies instance references:

Semicolon insertion

My inner Douglas-Crockford is bristling at this a bit, to be honest. Semi-colons are optional. You might notice I haven’t used any in the code above. The rule seems to be that if an expression can be evaluated, then it will be. So be careful typing code like:

Because you’ll get this:

I use three ways to cope with this:

Everything on one line. Not nice with long lines.

Use the backreferences. Usually only used when I forget about semicolon insertion, and accompanied by me kicking myself.

Move your dots. A bit surprising-looking but works OK. Least-worst option IMHO.

NB there is an open bug to prevent this behaviour during multi-line paste

Pasting content

There seems to be a bug which prevents pasting more than 2 lines of code. It’s reported here. That bug is marked as RESOLVED but still the bug persists in JDK 9.0.1 which is the latest one (on Linux at least). The workaround is:

This launches your $EDITOR which you can paste as many lines as you like into, then save & exit and jshell evaluates it all.

Conclusion