JShell is a Java read-eval-print loop, i.e. REPL, an interactive shell. It’s only introduced in Java 9 in 2017.

2017 is a long time ago!? Well not quite if you focus on Android development. Android was long stuck in Java 8. Only in December of 2020, support for Java versions up to 11 was announced.

So what’s good about REPL?

Traditionally, when we develop a program with Java language (and many other languages), we type our code in an editor. At this stage, one only knows what may work based on experience and knowledge. On some new things we are not sure. So we keep develop in the “dark” to some certain stage when all necessary pieces are thought to be put in. Then we do a build/compile of the code (build takes some time), only to find there are a lot of errors with the code. So we go through the errors, and if we are lucky enough some errors point to corresponding statements, we then check about the corresponding code statements to figure out what are wrong, which can take very long time. With modern editor or IDE’s, this can be minimized as grammatically errors are indicated in the editor when one types. Then we run the code to see what will happen. One is lucky (or one really is just doing some kids’ work) that it just runs the way one intended. So we revisit the code and see what are improper, despite all statements are grammatically correct. We go about checking on the things we are not too sure about. We ponder about them, modify them in some ways and re-build and rerun. Again not quite right…

So you know all this.

Now REPL comes to rescue. Enter “jshell” in a terminal:

$ jshell
|  Welcome to JShell -- Version 18.0.2-ea
|  For an introduction type: /help intro

jshell> 

Say now you want to figure out how to get the correct regex to extract the content from the following type of HTML statement:

<h1>Nayeem loves counseling</h1>

In jShell, you enter (just the necessary plain Java statements, no need for wrapping in a function or a class):

jshell> String text = "<h1>Nayeem loves counseling</h1>"

jshell responds:

   ...> 
text ==> "<h1>Nayeem loves counseling</h1>"

Enter another statement:

jshell> text.replaceAll("<*>", "");
$3 ==> "<h1Nayeem loves counseling</h1"

There, you see some result right away. But this result is not what you wanted, but you learned that immediately. So you make some changes:

jshell> text.replaceAll("<[^>]*>", "");
   ...> 
$2 ==> "Nayeem loves counseling"

Bang! That’s what you wanted. Then you can put it in you code editor and this part will work when you build and run the code because it’s been tested.

Cheers! Santé! Prost!