JShell (REPL) – The Java Shell

In earlier JDK, we did not have the luxury of running code using a command line interface. For learning new functions such as the matches function of regular expression API and many more, we had to write a necessary skeleton of Java, public static void main(String[] args), and go through the compilation and execution phase.

Java 9 introduced JShell, a command line tool. It uses the Read-Eval-Print Loop (REPL) principle to provide a command line interface to interact with the Java platform and provide an interactive way of running a program without writing necessary skeletons.

JShell came up with a parser that parses submitted code and identifies different types such as a variable, a declared method, loop, and many more, and put them all together in a dummy skeleton to make a complete Java program to pass it to the compiler. Based on the inputs compiler, it converts it into byte code. During this process, a file is not created, so it will all be saved in memory. At the end, the generated byte code is used by JVM to load and execute.

JShell is located in the bin directory of shipped JDK 9. Using a command interface, traverse to the bin directory and type command JShell to start the tool:

Let’s consider a program that we used to write in IDE. Here is a simple program to print a string message into uppercase:

module javaIntroduction {
}
package com.packt.java9dependency.examples;
public class Main {
public static void main(String[] args) {
String s = "hello java module system".toUpperCase();
System.out.println(s);
}
}

Now, we can get quick output of the preceding string message by directly writing a statement in the JShell tool, declaring variables and println statements is not required. JShell provides various command features that make a developer's life easy when writing quick code snippets.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.52.188