JShell with Java 9+

Having sandboxes to isolate and test hypotheses while programming is a fantastic way to confirm knowledge.

REPLs are a great example of one of these sandboxes. Sometimes you may have a belief about how a certain language feature works, but need to confirm it. You could implement this in whatever large project you are working in, although this could lead to many problems.

The cost of spinning up an existing project can be prohibitive, and discourage validating your concerns in the first place.

There could also be unforeseen side effects from your existing codebase with blackbox functions which ultimately could give you a false positive/negative.

Enter Java REPLs. Historically this Java REPL by Albert Latacz has been one of the go to Java REPLs, and it has been a fantastic resource. This however has now been deprecated, with the release of Java 9 which has a built in Java REPL.

If you are an Android developer like me however, you may not have Java 9 installed, let alone set as the main Java version in your PATH.

My solution to this has been to use jenv to manage multiple Java versions (which is going to become more relevant as more Java versions start coming out at a 6-month release cadence).

Once jenv is installed, I download the JDKs that I want, which would be Java 9+ to be able to use jshell, and then add that JDK to jenv.

~/
➜ jenv add /Library/Java/JavaVirtualMachines/jdk1901.jdk/Contents/Home
 oracle64–9.0.1 added

Once that is installed I use the jenv local feature to set the Java version for some sandbox directory to Java 9+ so that I do not affect my global Java version, and existing Android projects.

~/
➜ mkdir sandbox; cd sandbox

~/sandbox
➜ jenv local 9.0

~/sandbox
➜ java -version
java version “9.0.1”
Java(TM) SE Runtime Environment (build 9.0.1+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed mode)

Now everything is setup to start using jshell in this directory!

~/sandbox
➜ jshell
| Welcome to JShell — Version 9.0.1
| For an introduction type: /help intro

jshell> System.out.println(“Hello, world!”)
Hello, world!

There are a bunch of cool features that you can explore to super power your usage of jshell that are worth exploring. There are also more features of jenv that I would encourage exploring, and also consider aliases to make it more convenient for your workflow.