JAVA9:REPL Environment and programming

Source: Internet
Author: User
Tags vars mercurial version control system

Subtitle: Java 9 begins to provide REPL environment--jshell may change the way programmers use and learn Java

Translator Note: Recommend an online REPL demo environment: Java Web Console http://www.javarepl.com/console.html

You can try to execute some simple Java code in it, such as:

System.out.println("See See REPL")

System.getProperty("user.name")

2 + 2 * 5

A joke says: Why do programmers seem to be doing nothing all day? Because they are compiling the code ...

What are the benefits of having an interactive console? The translator's experience is simply too convenient to test strings, regular, and so simple programs.

Maybe you've written Clojure and Scala code, or you've written a program in LISP. If you have loved them deeply, then you must be quite happy with REPL. REPL, All-in- read-eval-print-loop one, is a shell interface that reads input from line-by-row, computes the value of the input, and then prints out the execution results. This is a very friendly instant interactive environment, I love it!

When using REPL, the interactive code is written and executed immediately after the input is completed. It is expected that when Java 9 is released in 2016, a fully functional REPL environment, named Jshell (codenamed Kulla), will be provided. This article introduces Java REPL briefly, and then explores how it might be used when writing Java code in the future.

God Horse! Does Java actually have no REPL environment?

For a broadly stable language like Java, it is necessary to have a REPL environment! But in fact not all languages support REPL, such as Java (formerly). It can be said that Java developers are much more than other languages and should provide a REPL environment. Java also has an environment similar to REPL: Java BeanShell, but this project is not fully functional and supports only a subset of Java syntax.

REPL can reduce the steering time of thinking

Shorten the steering time and even feedback is important to the programmer's health. For programmers who want this feature, REPL is a very power tool. In general, it is immediately possible to see the results of execution as the most efficient programming method for the human brain. With the Java REPL Environment, developers can write code, execute, and continue writing. No longer need to interrupt thinking, to compile, package, execute, and then, strange, just think of where?

While many programs and systems written in Java are far beyond the scope of an interactive command-line environment, if a REPL is built into the JDK, we can use it very easily at any time, but the frequency should be high. In fact, Jshell also opens the API, which makes it easy for IDE environments to integrate it. Of course, most IDE support is also required to be realistic, and developers need to use the latest ide!

Getting Started with Jshell

To explain, when writing this article, the JDK 9 Developer Preview version does not include the Kulla project because REPL is still in the development phase. So you need to clone Mercurial inside the project source code, compile the JDK, but also compile the jshell yourself.

This process can take several hours, especially if you are not familiar with the JDK source code. You must disable the warning as an error, if you are compiling on OSX, make sure that you have installed XCode and xquartz the FreeType library. You can follow the steps below to install and run the Kulla project.

1. Installing Java 9

With Jshell, you need to download and install the latest Java 9 developer preview. After the installation is complete, you JAVA_HOME need to set environment variables, which can then be executed at the command line java - version to check if the configuration is correct. There are some pits in the middle, especially on the OSX system, so special reminders!

2. Installing Kulla Mercurial and projects

Kulla is a OPENJDK project that uses a distributed version control system Mercurial, so you need to clone the Mercurial warehouse and perform the compilation.

Next is the Clone Kulla library:

hg clone http://hg.openjdk.java.net/kulla/dev/kulla

Then configure the compilation environment:

cd kullabash ./configure --disable-warnings-as-errorsmake images
3. Compile and run Repl

Here is the command to compile REPL:

cd langtools/replbash ./scripts/compile.sh

Use the following script to start:

As explained earlier, Java's REPL feature is not yet available to the general user, but we programmers can play it first!

Perform mathematical operations

What can Jshell do? Let's start with a simple math operation, using a ready-made java.lang.Math library:

Listing 1 using REPL to calculate mathematical expressions

$ bash ./scripts/run.sh |  Welcome to JShell -- Version 0.710|  Type /help for help-> Math.sqrt( 144.0f );|  Expression value is: 12.0|    assigned to temporary variable $1 of type double-> $1 + 100;|  Expression value is: 112.0|    assigned to temporary variable $2 of type double-> /vars|    double $1 = 12.0|    double $2 = 112.0-> double val = Math.sqrt( 9000 );|  Added variable val of type double with initial value 94.86832980505137

Here we calculate the square root of a number and add up to two numbers. This is not complicated and you can see that the /var command is used to display the list of variables created in the Jshell session. You can also refer to the value of an unassigned expression through the dollar sign ($). Finally, a new variable is created and assigned a value. "The Web console does not support commands that start with this slash"

Defining methods

Now we're going to do something interesting. In this example, we define a method to calculate the Fibonacci sequence (Fibonacci sequence). After the method definition, we can use /methods the command to view the methods defined in the session. Finally, our code calls the function and prints out the sequence corresponding to those numbers.

Listing 2 computes the Fibonacci sequence

$ bash ./scripts/run.sh |  Welcome to JShell -- Version 0.710|  Type /help for help-> long fibonacci(long number) {       if ((number == 0) || (number == 1))          return number;       else          return fibonacci(number - 1) + fibonacci(number - 2);    }|  Added method fibonacci(long)-> /methods|    fibonacci (long)long-> fibonacci( 12 )|  Expression value is: 144|    assigned to temporary variable $1 of type long-> int[] array = { 1,2,3,4,5,6,7,8 };|  Added variable array of type int[] with initial value [[email protected]-> for( long i : array ) { System.out.println(fibonacci( i )); }1123581321

You can also redefine the Fibonacci method and execute the same code in the same Jshell window. Because of the support for this iterative substitution feature, we can quickly execute, modify, and test new algorithms with REPL.

Listing 3 overriding methods in REPL

-> long fibonacci(long number) {     return 1;   }|  Modified method fibonacci(long)-> for( long i : array ) { System.out.println(fibonacci( i )); }1111111
Defining classes

The following code shows how to define a complete class in Jshell and then reference the class in an expression--the entire process is executed in REPL. Here we can create and test the code dynamically, and we can experiment with and replace the new code.

Listing 4 dynamically defining classes

MacOSX:repl tobrien$ bash ./scripts/run.sh |  Welcome to JShell -- Version 0.710|  Type /help for help->  class Person {         public String name;         public int age;         public String description;         public Person( String name, int age, String description ) {             this.name = name;             this.age = age;             this.description = description;         }         public String toString() {             return this.name;         }     }|  Added class Person-> Person p1 = new Person( "Tom", 4, "Likes Spiderman" );|  Added variable p1 of type Person with initial value Tom-> /vars|    Person p1 = Tom

While dynamic definition classes are powerful, they do not meet the needs of our developers, after all, writing long, long code in an interactive shell environment is a very earthy practice. This brings out the concept of history , which can be loaded in a previously saved state when the REPL is started. Use /history the command to list all statements and expressions that have been executed in REPL.

Listing 5 query history/history

-> /historyclass Person {    public String name;    public int age;    public String description;    public Person( String name, int age, String description ) {        this.name = name;        this.age = age;        this.description = description;    }    public String toString() {        return this.name;    }}Person p1 = new Person( "Tom", 4, "Likes Spiderman" );Person p2 = new Person( "Zach", 10, "Good at Math" );/varsp1p2/history

We can also save the REPL history to a file that can be loaded again later. Examples are as follows:

-> /save output.repl-> /reset|  Resetting state.-> /vars-> /open output.repl-> /vars|    Person p1 = Tom|    Person p2 = Zach

/savecommand to save the REPL history to a file, the command /reset resets the state of the REPL, and the /open command is used to read and execute a file in Repl. With Save and open functionality, programmers can set up more complex REPL scripts to configure different repl scenarios.

Modifying the definition of a class halfway

Jshell can also set the initialization profile and load it automatically. You can edit the source entry as you please. For example, if you want to modify the previously defined Person classes, you can use classes /list and /edit commands.

Listing 6 Modifying the person

-> /l   1 : class Person {           public String name;           public int age;           public String description;           public Person( String name, int age, String description ) {               this.name = name;               this.age = age;               this.description = description;           }           public String toString() {               return this.name;           }       }   2 : Person p1 = new Person( "Tom", 4, "Likes Spiderman" );   3 : Person p2 = new Person( "Zach", 10, "Good at Math" );   4 : p1   5 : p2-> /edit 1

The Execute /edit command opens a simple editor in which you can change the definition of the class, and the class is immediately updated.

What kind of high-tech is this?

If you look at how Clojure or LISP programmers write code, you'll find that they're primarily developed in a REPL environment. Instead of writing the code, compiling the build, and then executing it, as in Java, you're wasting a lot of time interacting when writing Java programs. If you're free, talk to a Scala or clojure programmer about REPL and see how they work.

Unlike Scala and Clojure, Java is a different language. Java developers don't spend too much time focusing on a few lines of common code, and the logic of a Lisp program can be contained in only a few lines of core code. Most Java programs need to be installed first, configured to work properly, although the latest version of the language reduces the number of lines of code to write, but we always casually can write in Java tens of thousands of lines of code complex system. The classes cited above are Person not very useful, and the most valuable code in Java is often very complex and difficult to write in REPL environments.

The programming environment for Scala and Clojure developers is called "Iterative development (Emerick iterative)" by the author of Clojure programming Chas Development, because it does not need to rely on file systems. Java programs need to rely on a lot of class libraries, have complex dependencies, and may also rely on containers such as Tomcat or Tomee. So I think that programming for REPL doesn't take the place of traditional IDE programming. However, I think Java's repl will be used better in these places.

1. Learn Java

Because Java development requires a lot of configuration. For beginners, using REPL can quickly understand grammar and basic concepts. The Java 9 repl will be a quick way to get started with the new starter programmer.

2. Learn and try out a new class library

Java has hundreds of easy-to-use open source class libraries, such as math, date and time library, and so on. In the days without REPL, write a bunch of "public static void main" every time to test. But if you have a command-line interaction environment, you can see the results of the execution as soon as you enter the key code.

3. Rapid prototyping

This is similar to Clojure and Scala development, and if you need to focus on a problem, using REPL can easily iterate through classes and algorithms. Instead of waiting for the compilation to complete, you can quickly adjust the definition of a class, reset Repl, and then try again. "Like regular match, string intercept, etc."

4. Integration with the Build tool

Gradle provides an interactive "shell" model, and the MAVEN community has introduced similar tools. We can reduce the complexity of the build by REPL while controlling the operation of other systems.

Future

I think in the next few years, with the popularity of JAVA9, REPL will increasingly affect the way we develop and program. Of course, the Java community also needs time to slowly adapt to the new development approach, summarizing and crossing the REPL of beauty and pitfalls.

I don't think most Java programmers will often use REPL for development, but new programmers will slowly get used to the REPL environment as a way to learn java. As new Java programmers and REPL spend a good time, there is no doubt that it will change the way we build and develop Java programs.

Reference article:

Original link: What REPL means for Java

Original date: August 13, 2015

Translation Date: September 16, 2015

Translators: Anchor Http://blog.csdn.net/renfufei

JAVA9:REPL Environment and programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.