Thursday, June 23, 2016

JShell (Java REPL) Uses

This post explains the uses of the Java JShell REPL. There are three main uses for Java 9's new JShell. First it's great for education. Second, it's great for investigation of APIs that are unfamiliar to you. Third, it is wonderful for quick prototyping of tricky code. So the Java REPL is best suited for education, investigation, and prototyping.

JShell REPL Needed for Schools

Schools have special needs when it comes to teaching basic Java programming. For example, when you're teaching a fist time programmer, especially a child, how to do basic Java, you don't want to start out by explaining packages, classes, methods and scoping. Here is the most basic first Java program you could introduce a child or first-time programmer to.


public class HelloWorldWithoutREPL {
  public static void main(String[] args) {
    System.out.println("Hello World!");
  }
}

Compare that to the following introductory program you can use when JShell is the platform for showing basic code to a student.


printf("Hello World!")


How about introducing threading to a new student. When beginning a discussion about the sleep() method, would an instructor prefer to begin with this?


public class FirstSleep {
  public static void main(String[] args) {
    System.out.printf("123");
    try {
      Thread.sleep(3000);
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
    System.out.printf("456");
  }
}

Or would the instructor prefer to use this example?


printf("123");Thread.sleep(3000);printf("456");

When using the Java REPL, instructors don't need to waste their time telling students to ignore code that they don't need to learn, yet. JShell is a great tool for educators. It allows instructors to keep lessons and homework focused on the Java topics at hand, instead of all the decoration that comes along with the Java language.

Easy API Investigation Using JShell

When you're trying to test poorly documented API's in Java, you don't want to deal with writing full-blown applicaitons just to figure out the holes in the documentation. You want to be able to write some code, press enter, and see the result. Then when you want to repeat the process over and over until you figure out each important method and attribute.

JShell is perfect for this kind of API experimentation.

Suppose you have a math library that promises to save your company a fortune, or better yet make your company a fortune. However, the writer of the Java library wasn't nearly as skilled as English as he was at finances. You could follow steps similar to these to get the library into JShell and experiment with it.

For this example, I'm going too use a math library from Apache Commons. Apache Commons is fairly well documented, but let's use it anyway.


  1. Download the commons-math.jar from http://commons.apache.org
  2. Start up JShell by entering 'jshell' at the command line.
  3. Add the commons math JAR to JShell's classpath by entering '/classpath' followed by the fully qualified path to the JAR file. Don't be afraid of typing in a long file path. JShell supports tab completion of files and directories.
  4. Enter the following two lines of code.

import org.apache.commons.math3.analysis.differentiation.*
new DerivativeStructure(1, 3, 0, 2.5)

You should now have a JShell temp variable named dollar sign followed by some number. For example the temp variable might be called '$2'. You can call methods on your DerivativeStructure object and see the results right away. You don't have to waste time saving files and compiling every time you want to try a different method on the DerivativeStructure object.

The result will be something like the following.


jshell> printf("y'  = " + $2.getValue())
y'  = 2.5
jshell> printf("y'  = " + $2.getPartialDerivative(1))
y'  = 1.0
jshell> printf("y'' = " + $2.getPartialDerivative(2))
y'' = 0.0

As you can see, checking out new API's is quick and easy using JShell.

JShell for Quick Prototyping

Sometimes you have to write a tricky bit of code that you're almost certain to get wrong several times before you get it right. A great example is dealing with complex regex patterns. JShell makes manually testing out tricky snippets of code quick and painless.

Continuing with using regex patterns as an example, imagine you need to find the first name, last name, and birthdate of an applicant in an OCR'ed form and place those three fields in a database. Writing the regex could get pretty nasty. Suppose you want to test out each regular expression before adding it to your program.

You might have a line of data that looks like the following.


Thomas Jefferson   4/13/1743

Then you want to test that your code finds the birth month correctly. You might enter the following into JShell.


jshell> "Thomas Jefferson   4/13/1743"
$7 ==> "Thomas Jefferson   4/13/1743"

jshell> $7.matches("\\w*\\s\\w*\\s*(\\d+)/\\d+/\\d+")
$26 ==> true

You can test it simply by pressing the up arrow, changing the regex, and hitting enter again. Making  corrections to the regular expressions for odd edge cases is just a matter of entering a new string and testing against that. Prototyping code snippets has never been easier.

Summary

JShell's main three uses are education, investigation and prototyping. In some cases, you may even find yourself doing your math homework in it, or simple programs to solve other problems too tricky for a cheap calculator. Either way, JShell is an incredible addition to Java. Be sure to check out my other Java Shell REPL tutorials!

2 comments:

  1. JShell is one of my favorite parts of Java by far, and is why I still recommend Java as a programming language for beginning coders.

    - Fred

    ReplyDelete
    Replies
    1. I have read your blog its very attractive and impressive. I like it your blog.

      Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

      Java Online Training Java Online Training JavaEE Training in Chennai Java EE Training in Chennai

      Delete