Home Programming Java 9 with JShell

Java 9 with JShell

By Gaston C. Hillar
books-svg-icon Book
Subscription FREE
eBook + Subscription $15.99
eBook $43.99
Print + eBook $54.99
READ FOR FREE Free Trial for 7 days. $15.99 p/m after trial. Cancel Anytime! BUY NOW BUY NOW BUY NOW
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
READ FOR FREE Free Trial for 7 days. $15.99 p/m after trial. Cancel Anytime! BUY NOW BUY NOW BUY NOW
Subscription FREE
eBook + Subscription $15.99
eBook $43.99
Print + eBook $54.99
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
  1. Free Chapter
    JShell – A Read-Evaluate-Print-Loop for Java 9
About this book
The release of Java 9 has brought many subtle and not-so-subtle changes to the way in which Java programmers approach their code. The most important ones are definitely the availability of a REPL, known as JShell, which will make experiments and prototyping much more straightforward than the old IDE-based project-led approach. Another, more subtle change can be seen in the module system, which will lead to more modularized, maintainable code. The techniques to take full advantage of object-oriented code, functional programming and the new modularity features in Java 9 form the main subjects of this book. Each chapter will add to the full picture of Java 9 programming starting out with classes and instances and ending with generics and modularity in Java.
Publication date:
March 2017
Publisher
Packt
Pages
408
ISBN
9781787282841

 

Chapter 1. JShell – A Read-Evaluate-Print-Loop for Java 9

In this chapter, we will start our journey toward object-oriented programming with Java 9. You will learn how to launch and work with a new utility introduced with Java 9 that will allow us to easily run Java 9 code snippets and print their results: JShell. This utility will make it easy for you to learn object-oriented programming. We will do the following:

  • Get ready for our journey toward OOP (Object-Oriented Programming) with Java 9

  • Install the required software on Windows, macOS, or Linux

  • Understand the benefits of working with a REPL (Read-Evaluate-Print-Loop) utility

  • Check default imports and use auto-complete features

  • Run Java 9 code in JShell

  • Evaluate expressions

  • Work with variables, methods, and sources

  • Edit the source code in our favorite external code editor

  • Load source code

 

Getting ready for our journey toward OOP with Java 9


In this book, you will learn to take advantage of all the object-oriented features included in the Java programming language version 9, known as Java 9. Some of the examples might be compatible with previous Java versions, such as Java 8, Java 7, and Java 6, but it is essential to use Java 9 or later because this version is not backwards compatible. We won't write code that is backwards compatible with previous Java versions because our main goal is to work with Java 9 or later and to use its syntax and all of its new features.

Most of the time, we won't use any IDE (Integrated Development Environment), and we will take advantage of JShell and many other utilities included in the JDK. However, you can use any IDE that provides a Java 9 REPL to work with all the examples. You will understand the benefits of working with a REPL in the next sections. You will definitely benefit from an IDE in the last chapter where you will explore the new modularity features introduced with Java 9.

Note

You don't need any previous experience with the Java programming language to work with the examples in the book and learn how to model and create object-oriented code with Java 9. If you have some experience with C#, C++, Python, Swift, Objective-C, Ruby, or JavaScript, you will be able to easily learn Java's syntax and understand the examples. Many modern programming languages have been borrowing features from Java and vice versa. Therefore, any knowledge of these languages will be extremely useful.

In this chapter, we will install the required software on Windows, macOS, or Linux. We will understand the benefits of working with a REPL, specifically, JShell, to learn object-oriented programming. We will learn how to run Java 9 code in the JShell and how to load the source code samples in the REPL. Finally, we will learn how to run Java code on Windows, macOS, and Linux from the command line or terminal.

 

Installing the required software on Windows, macOS, or Linux


We must download and install the latest version of JDK 9 (Java Development Kit 9) for our operating system from https://jdk9.java.net/download/. We must accept the license agreement for Java to download the software.

As happened with previous versions, JDK 9 is available on many different platforms, including but not limited to the following:

  • Windows 32-bit

  • Windows 64-bit

  • macOS 64-bit (formerly known as Mac OS X or simply OS X)

  • Linux 32-bit

  • Linux 64-bit

  • Linux on ARM 32-bit

  • Linux on ARM 64-bit

Once we have completed the installation for the appropriate version of JDK 9 based on our operating system, we can add the bin sub-folder of the folder in which JDK 9 has been installed to the PATH environment variable. This way, we would be able to launch the different utilities from any folder in which we are located.

Note

If we don't add the bin sub-folder of the folder in which JDK 9 has been installed to the PATH environment variable in our operating system, we will always have to use the full path to the bin sub-folder when executing the commands. In the next instructions to launch the different Java command-line utilities, we will assume that we are located in this bin sub-folder or that the PATH environment variable includes it.

Once we have installed JDK 9, and added the bin folder to the PATH environment variable, we can run the following command in Windows Command Prompt or in macOS or Linux Terminal:

javac -version

The previous command will display the current version for the primary Java compiler included in the JDK that compiles Java source code into Java bytecodes. The version number should start with 9, as shown in the next sample output:

javac 9-ea

If the results of the previous command display a version number that doesn't start with 9, we must check whether the installation completed successfully. In addition, we have to make sure that the PATH environment variable doesn't include paths to previous versions of the JDK and that it includes the bin folder for the recently installed JDK 9.

Now, we are ready to launch JShell. Run the following command in Windows Command Prompt or in macOS or Linux Terminal:

jshell

The previous command will launch JShell, display a welcome message that includes the JDK version being used, and the prompt will change to jshell>. Whenever we see this prompt, it means we are still in JShell. The following screenshot shows JShell running in a Terminal window on macOS.

Note

If we want to leave JShell at any time, we just need to press Ctrl + D in a Mac. Another option is to enter /exit and press Enter.

Understanding the benefits of working with a REPL

Java 9 introduced an interactive REPL command-line environment named JShell. This tool allows us to execute Java code snippets and get immediate results. We can easily write code and see the results of its execution without having to create a solution or project. We don't have to wait for the project to finish the build process to check the results of executing many lines of code. JShell, as any other REPL, facilitates exploratory programming, that is, we can easily and interactively try and debug different algorithms and structures.

Note

If you have worked with other programming languages that provide a REPL or an interactive shell such as Python, Scala, Clojure, F#, Ruby, Smalltalk, and Swift among many others, you already know the benefits of working with a REPL.

For example, imagine that we have to interact with an IoT (Internet of Things) library that provides Java bindings. We have to write Java code to use the library to control a drone, also known as a UAV (Unmanned Aerial Vehicle). The drone is an IoT device that interacts with many sensors and actuators, including digital electronic speed controllers linked to engines, propellers, and servomotors.

We want to be able to write a few lines of code to retrieve data from sensors and control the actuators. We just need to make sure things work as explained in the documentation. We want to make sure that the values read from the altimeter change when we move the drone. JShell provides us with the appropriate tool to start interacting with the library in a few seconds. We just need to launch JShell, load the library, and start writing Java 9 code in the REPL. With previous Java versions, we would have needed to create a new project from scratch and write some boilerplate code before we could start writing the first lines of code that interacted with the library. JShell allows us to start working faster and reduces the need to create an entire skeleton to start running Java 9 code. JShell allows interactive exploration of APIs (Application Programming Interfaces) from a REPL.

We can enter any Java 9 definition in JShell. For example, we can declare methods, classes, and variables. We can also enter Java expressions, statements, or imports. Once we have entered the code to declare a method, we can enter a statement that uses the previously defined method and see the results of the execution.

JShell allows us to load source code from a file, and therefore, you will be able to load the source code samples included in this book and evaluate them in JShell. Whenever we have to work with source code, you will know the folder and the file from which you can load it. In addition, JShell allows us to execute JShell commands. We will learn about the most useful commands later, in this chapter.

JShell allows us to call the System.out.printf method to easily format output we want to print. We will take advantage of this method in our sample code.

Note

JShell disables some features from Java 9 that aren't useful in the interactive REPL. Whenever we have to work with these features in JShell, we will make it clear that JShell will disable them and we will explain their effects.

The semicolon (;) is optional at the end of a statement in JShell. However, we will always use a semicolon at the end of each statement because we don't want to forget that we must use semicolons when we write real-life Java 9 code in projects and solutions. We will only omit the semicolon at the end of a statement when we enter expressions to be evaluated by JShell.

For example, the following two lines are equivalent and both of them will print "Object-Oriented Programming rocks with Java 9!" as a result of their execution in JShell. The first line doesn't include a semicolon (;) at the end of the statement and the second line includes the semicolon (;). We will always use the semicolon (;) as in the second line, to keep consistency.

System.out.printf("Object-Oriented Programming rocks with Java 9!\n")
System.out.printf("Object-Oriented Programming rocks with Java 9!\n");

The following screenshot shows the results of executing the two lines in JShell running on Windows 10:

In some examples, we will take advantage of the fact that JShell provides us networking access. This feature is extremely useful to interact with Web Services. However, you have to make sure that you don't have JShell blocked in your firewall configuration.

Note

Unluckily, at the time I was writing this book, JShell didn't include syntax highlighting features. However, you will learn how to use our favorite editor to write and edit code that we can then execute in JShell.

Checking default imports and using auto-complete features

By default, JShell provides a set of common imports and we can use the import statement to import the necessary types from any additional package we might need to run our code snippets. We can enter the following command in JShell to list all the imports:

/imports

The following lines show the results of the previous command:

|    import java.io.*
|    import java.math.*
|    import java.net.*
|    import java.nio.file.*
|    import java.util.*
|    import java.util.concurrent.*
|    import java.util.function.*
|    import java.util.prefs.*
|    import java.util.regex.*
|    import java.util.stream.*

As happens when we write Java code outside of JShell, we don't need to import the types from the java.lang package because they are imported by default and they aren't listed when we run the /imports command in JShell. Thus, by default, JShell provides us access to all the types in the following packages:

  • java.lang

  • java.io

  • java.math

  • java.net

  • java.nio.file

  • java.util

  • java.util.concurrent

  • java.util.function

  • java.util.prefs

  • java.util.regex

  • java.util.stream

JShell provides auto-completion features. We just need to press the Tab key whenever we want to have assistance from the auto-complete feature, as done when we work with the Windows Command Prompt or the Terminal in macOS or Linux.

Sometimes, there are too many options that start with the first characters we entered. In these cases, JShell provides us with a list of all the available options to provide us help. For example, we can enter S and press the Tab key. JShell will list all the types imported from the previously listed packages that start with an S. The following screenshot shows the results in JShell:

We want to enter System. Considering the previous list, we will just enter Sys to make sure that System is the only option that starts with Sys. Basically, we are cheating to understand how auto-completion works in JShell. Enter Sys and press the Tab key. JShell will display System.

Now, enter a dot (.) followed by an o (you will have System.o) and press the Tab key. JShell will display System.out.

Next, enter a dot (.) and press the Tab key. JShell will display all the public methods declared in System.out. After the list, JShell will include System.out. again to allow us to continue entering our code. The following screenshot shows the results in JShell:

Enter printl and press the Tab key. JShell will complete to System.out.println(, that is, it will add an n and open parenthesis ((). This way, we just have to enter the arguments for the method because there was just one method that started with printl. Enter "Auto-complete is helpful in JShell"); and press Enter. The following line shows the complete statement:

System.out.println("Auto-complete is helpful in JShell");

The following screenshot shows the results in JShell after running the previous line:

 

Running Java 9 code in JShell


Now, we want to run Java 9 code in JShell and understand what happens after we enter each code snippet. Press Ctrl + D to exit the current JShell session. Run the following command in the Windows Command Prompt or in a macOS or Linux Terminal to launch JShell with a verbose feedback:

jshell -v

The verbose feedback will provide us additional details about what JShell does after it executes or evaluates each code snippet. Enter the following code in JShell to create a new method named calculateRectangleArea. The method receives a width and a height for a rectangle and returns the result of the multiplication of both values of type float:

float calculateRectangleArea(float width, float height) {
    return width * height;
}

After we enter the previous lines, JShell will display the next message indicating it has created a method named calculateRectangleArea with two arguments of float type:

|  created method calculateRectangleArea(float,float)

Note

Notice that all the messages written by JShell start with a pipe symbol (|).

Enter the following command in JShell to list the current active snippets of code that we have typed and executed so far in the current session:

/list

The following lines show the results. Notice that JShell prefaces the code snippet with the snippet id, that is, a unique number that identifies each code snippet. JShell will display the following lines as a result of the previous command. The code snippet that created the calculateRectangleArea method has been assigned 1 as the snippet id.

   1 : float calculateRectangleArea(float width, float height) {
           return width * height;
       }

Enter the following code in JShell to create a new float variable named width and initialize it with 50:

float width = 50;

After we enter the previous line, JShell will display the next message indicating it has created a variable named width of float type and it assigned the value 50.0 to this variable:

width ==> 50.0
|  created variable width : float

Enter the following code in JShell to create a new float variable named height and initialize it with 25:

float height = 25;

After we enter the previous line, JShell will display the next message indicating it has created a variable named height of the float type and it assigned the value 25.0 to this variable:

height ==> 25.0
|  created variable height : float

Enter float area = ca and press the Tab key. JShell will complete to float area = calculateRectangleArea(, that is, it will add lculateRectangleArea and open parenthesis ((). This way, we just have to enter the two arguments for the method because there was just one method that started with ca. Enter width, height); and press Enter. The following line shows the complete statement:

float area = calculateRectangleArea(width, height);

After we enter the previous line, JShell will display the next message indicating it has created a variable named area of the float type and it assigned the result of calling the calculateRectangleArea method with the previously declared width and height variables as arguments. The method returns 1250.0 as a result and it is assigned to the area variable.

area ==> 1250.0
|  created variable area : float

Enter the following command in JShell to list the current active snippets of code that we have typed and executed so far in the current session:

/list

The following lines show the results. Notice that JShell prefaces the code snippet with the snippet id, that is, a unique number that identifies each code snippet. JShell will display the following lines as a result of the previous command:

   1 : float calculateRectangleArea(float width, float height) {
           return width * height;
       }
   2 : float width = 50;
   3 : float height = 25;
   4 : float area = calculateRectangleArea(width, height);

Enter the following code in JShell to display the values for the width, height, and area variables with a call to System.out.printf. The first %.2f in the string we pass as a first argument to System.out.printf makes the next argument after the string (width) to be displayed as a floating point number with two decimal places. We repeat %.2f twice to display the height and area variables as floating point numbers with two decimal places.

System.out.printf("Width: %.2f, Height: %.2f, Area: %.2f\n", width, height, area);

After we enter the previous line, JShell will format the output with System.out.printf and will print the next message followed by the name of a scratch variable:

Width: 50.00, Height: 25.00, Area: 1250.00
$5 ==> java.io.PrintStream@68c4039c
|  created scratch variable $5 : PrintStream

Evaluating expressions

JShell allows us to evaluate any valid Java 9 expression, as we might do when we use an IDE and the typical expression evaluation dialog box. Enter the following expression in JShell:

width * height;

After we enter the previous line, JShell will evaluate the expression and it will assign the results to a scratch variable whose name starts with $ and continues with a number. JShell displays the scratch variable name, $6, the value assigned to the variable that indicates the result of evaluating the expression, 1250.0, and the type for the scratch variable, float. The next lines show the message displayed in JShell after we enter the previous expression:

$6 ==> 1250.0
|  created scratch variable $6 : float

Notice that the name for the scratch variable might be different. For example, instead of $6, it might be $7 or $8. We can run a code snippet that uses the previously created scratch variable as we do with any other variable created in the current JShell session. Enter the following code in JShell to display the value for the $6 variable as a floating point number with two decimal places. Make sure you replace $6 with the scratch variable name that JShell generated.

System.out.printf("The calculated area is %.2f", $6);

After we enter the previous line, JShell will format the output with System.out.printf and will print the next message:

The calculated area is 1250.00

We can also use the previously created scratch variable in another expression. Enter the following code in JShell to add 10.5 (float) to the value of the $6 variable. Make sure you replace $6 with the scratch variable name that JShell generated.

$6 + 10.5f;

After we enter the previous line, JShell will evaluate the expression and it will assign the results to a new scratch variable whose name starts with $ and continues with a number. JShell displays the scratch variable name, $8, the value assigned to the variable that indicates the result of evaluating the expression, 1260.5, and the type for the scratch variable, float. The next lines show the message displayed in JShell after we enter the previous expression:

$8 ==> 1250.5
|  created scratch variable $8 : float

Note

As happened before, the name for the scratch variable might be different. For example, instead of $8, it might be $9 or $10.

 

Working with variables, methods, and sources


So far, we have been creating many variables, and JShell created a few scratch variables after we entered expressions and they were successfully evaluated. Enter the following command in JShell to list the type, name, and value of the current active variables that have been created so far in the current session:

/vars

The following lines show the results:

|    float width = 50.0
|    float height = 25.0
|    float area = 1250.0
|    PrintStream $5 = java.io.PrintStream@68c4039c
|    float $6 = 1250.0
|    float $8 = 1260.5

Enter the following code in JShell to assign 80.25 (float) to the previously created width variable:

width = 80.25f;

After we enter the previous line, JShell will display the next message indicating it has assigned 80.25 (float) to the existing variable named width of the float type:

width ==> 80.25
|  assigned to width : float

Enter the following code in JShell to assign 40.5 (float) to the previously created height variable:

height = 40.5f;

After we enter the previous line, JShell will display the next message indicating it has assigned 40.5 (float) to the existing variable named height of the float type:

height ==> 40.5
|  assigned to height : float

Enter the following command in JShell again to list the type, name, and value of the current active variables:

/vars

The following lines show the results that reflect the new values we have assigned to the width and height variables:

|    float width = 80.25
|    float height = 40.5
|    float area = 1250.0
|    PrintStream $5 = java.io.PrintStream@68c4039c
|    float $6 = 1250.0
|    float $8 = 1260.5

Enter the following code in JShell to create a new method named calculateRectanglePerimeter. The method receives a width variable and a height variable for a rectangle and returns the result of the multiplication by 2 of the sum of both values of the float type.

float calculateRectanglePerimeter(float width, float height) {
    return 2 * (width + height);
}

After we enter the previous lines, JShell will display the next message indicating it has created a method named calculateRectanglePerimeter with two arguments of the float type:

|  created method calculateRectanglePerimeter(float,float)

Enter the following command in JShell to list the name, parameter types, and return the type of the current active methods that have been created so far in the current session:

/methods

The following lines show the results.

|    calculateRectangleArea (float,float)float
|    calculateRectanglePerimeter (float,float)float

Enter the following code in JShell to print the results of calling the recently created calculateRectanglePerimeter with width and height as the arguments:

calculateRectanglePerimeter(width, height);

After we enter the previous line, JShell will call the method and it will assign the results to a scratch variable whose name starts with $ and continues with a number. JShell displays the scratch variable name, $16, the value assigned to the variable that indicates the result returned by the method, 241.5, and the type for the scratch variable, float. The next lines show the message displayed in JShell after we enter the previous expression that called a method:

$16 ==> 241.5
|  created scratch variable $16 : float

Now, we want to make changes to the recently created calculateRectanglePerimeter method. We want to add a line to print the calculated perimeter. Enter the following command in JShell to list the source code for the method:

/list calculateRectanglePerimeter

The following lines show the results:

  15 : float calculateRectanglePerimeter(float width, float height) {
           return 2 * (width + height);
       }

Enter the following code in JShell to overwrite the method named calculateRectanglePerimeter with a new code that prints the received width and height values and then prints the calculated perimeter with calls to the System.out.printf method that works in the same way as the built-in printf method. We can copy and paste the pieces from the previously listed source code. The changes are highlighted here:

float calculateRectanglePerimeter(float width, float height) {
    float perimeter = 2 * (width + height);
    System.out.printf("Width: %.2f\n", width);
    System.out.printf("Height: %.2f\n", height);
    System.out.printf("Perimeter: %.2f\n", perimeter);
    return perimeter;
}

After we enter the previous lines, JShell will display the next messages indicating it has modified and overwritten the method named calculateRectanglePerimeter with two arguments of the float type:

|  modified method calculateRectanglePerimeter(float,float)
|    update overwrote method calculateRectanglePerimeter(float,float)

Enter the following code in JShell to print out the results of calling the recently modified calculateRectanglePerimeter with width and height as the arguments:

calculateRectanglePerimeter(width, height);

After we enter the previous line, JShell will call the method and it will assign the results to a scratch variable whose name starts with $ and continues with a number. The first lines display the output generated by the three calls to System.out.printf that we added to the method. Finally, JShell displays the scratch variable name, $19, the value assigned to the variable that indicates the result returned by the method, 241.5, and the type for the scratch variable, float.

The next lines show the messages displayed in JShell after we enter the previous expression that called the new version of the method:

Width: 80.25
Height: 40.50
Perimeter: 241.50
$19 ==> 241.5
|  created scratch variable $19 : float
 

Editing the source code in our favorite external code editor


We created a new version of the calculateRectanglePerimeter method. Now, we want to make similar changes to the calculateRectangleArea method. However, this time, we will take advantage of an editor to make it easier to make changes to the existing code.

Enter the following command in JShell to launch the default JShell Edit Pad editor to edit the source code for the calculateRectangleArea method:

/edit calculateRectangleArea

JShell will display a dialog box with JShell Edit Pad and the source code for the calculateRectangleArea method, as shown in the following screenshot:

JShell Edit Pad lacks most of the features we enjoy from code editors and we cannot even consider it a decent code editor. In fact, it just allows us to easily edit the source code without having to copy and paste from the previous listing. We will learn how to configure a better editor later.

Enter the following code in the JShell Edit Pad to overwrite the method named calculateRectangleArea with a new code that prints the received width and height values and then prints the calculated area with calls to the Sytem.out.printf method. The changes are highlighted here:

float calculateRectangleArea(float width, float height) {
    float area = width * height;
    System.out.printf("Width: %.2f\n", width);
    System.out.printf("Height: %.2f\n", height);
    System.out.printf("Area: %.2f\n", area);
    return area;
}

Click on Accept and then click on Exit. JShell will close the JShell Edit Pad and display the next messages indicating it has modified and overwritten the method named calculateRectangleArea with two arguments of the float type:

|  modified method calculateRectangleArea(float,float)
|    update overwrote method calculateRectangleArea(float,float)

Enter the following code in JShell to print the results of calling the recently modified calculateRectangleArea method with width and height as the arguments:

calculateRectangleArea(width, height);

After we enter the previous line, JShell will call the method and it will assign the results to a scratch variable whose name starts with $ and continues with a number. The first lines display the output generated by the three calls to System.out.printf that we added to the method. Finally, JShell displays the scratch variable name, $24, the value assigned to the variable that indicates the result returned by the method, 3250.125, and the type for the scratch variable, float. The next lines show the messages displayed in JShell after we enter the previous expression that called the new version of the method:

Width: 80.25
Height: 40.50
Area: 3250.13
$24 ==> 3250.125
|  created scratch variable $24 : float

The good news is that JShell allows us to easily configure any external editor to edit the code snippets. We just need to grab the complete path to the editor we want to use and run a command in JShell to configure the editor we want to launch whenever we use the /edit command.

For example, in Windows, the default installation path for the popular Sublime Text 3 code editor is C:\Program Files\Sublime Text 3\sublime_text.exe. If we want to use this editor to edit code snippets in JShell, we must run the /set editor command followed by the path enclosed in double quotes. We have to make sure that we replace the backslash (\) with double backslashes (\\) in the path string. For the previously explained path, we must run the following command:

/set editor "C:\\Program Files\\Sublimet Text 3\\sublime_text.exe"

After we enter the previous command, JShell will display a message indicating to us that the editor was set to the specified path:

| Editor set to: C:\Program Files\Sublime Text 3\sublime_text.exe

After we change the editor, we can enter the following command in JShell to launch the new editor to make changes to the source code for the calculateRectangleArea method:

/edit calculateRectangleArea

JShell will launch Sublime Text 3 or any other editor that we might have specified and will load a temporary file with the source code for the calculateRectangleArea method, as shown in the following screenshot:

Note

If we save the changes, JShell will automatically overwrite the method as we did when we used the default editor: JShell Edit Pad. After we make the necessary edits, we must close the editor to continue running Java code or JShell commands in JShell.

In any of the platforms, JShell will create a temporary file with the .edit extension. Thus, we can configure our favorite editor to use Java syntax highlighting whenever we open files with the .edit extension.

In macOS or Linux, paths are different than in Windows, and therefore, the necessary steps are different. For example, in macOS, in order to launch the popular Sublime Text 3 code editor when it is installed in the default path, we must run /Applications/Sublime Text.app/Contents/SharedSupport/bin/subl.

If we want to use this editor to edit code snippets in JShell, we must run the /set editor command followed by the complete path enclosed in double quotes. For the previously explained path, we must run the following command:

/set editor "/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl"

After we enter the previous command, JShell will display a message indicating to us that the editor was set to the specified path:

|  Editor set to: /Applications/Sublime Text.app/Contents/SharedSupport/bin/subl

After we change the editor, we can enter the following command in JShell to launch the new editor to make changes to the source code for the calculateRectangleArea method:

/edit calculateRectangleArea

JShell will launch Sublime Text 3 on macOS or any other editor that we might have specified and will load a temporary file with the source code for the calculateRectangleArea method, as shown in the following screenshot:

 

Loading source code


Of course, we don't have to enter the source code for each example. Auto-completion features are useful, but we will take advantage of a command that allows us to load source code from a file in JShell.

Press Ctrl + D to exit the current JShell session. Run the following command in the Windows Command Prompt or in a macOS or Linux Terminal to launch JShell again with a verbose feedback:

jshell -v

The following lines show code that declares the latest versions of the calculateRectanglePerimeter and calculateRectangleArea methods. Then, the code declares and initializes two variables of the float type: width and height. Finally, the last two lines call the previously defined methods with width and height as their arguments. The code file for the sample is included in the java_9_oop_chapter_01_01 folder, in the example01_01.java file.

float calculateRectanglePerimeter(float width, float height) {
    float perimeter = 2 * (width + height);
    System.out.printf("Width: %.2f\n", width);
    System.out.printf("Height: %.2f\n", height);
    System.out.printf("Perimeter: %.2f\n", perimeter);
    return perimeter;
}

float calculateRectangleArea(float width, float height) {
    float area = width * height;
    System.out.printf("Width: %.2f\n", width);
    System.out.printf("Height: %.2f\n", height);
    System.out.printf("Area: %.2f\n", area);
    return area;
}

float width = 120.25f;
float height = 35.50f;
calculateRectangleArea(width, height);
calculateRectanglePerimeter(width, height);

Once you have downloaded the source code for the book in a folder, you can use the /open command in JShell to load and execute one of the files from the source code. Before each code snippet, we always mention where the source code is located.

If the root folder for the source code in Windows is C:\Users\Gaston\Java9, you can run the following command to load and execute the previously shown source code in JShell:

/open C:\Users\Gaston\Java9\java_9_oop_chapter_01_01\example01_01.java

If the root folder for the source code in macOS or Linux is ~/Documents/Java9, you can run the following command to load and execute the previously shown source code in JShell:

/open ~/Documents/Java9/java_9_oop_chapter_01_01/example01_01.java

After we enter the previous command followed by the path based on our configuration and our operating system, JShell will load and execute the previously shown source code and will display the output generated after running the loaded code snippet. The following lines show the output:

Width: 120.25
Height: 35.50
Area: 4268.88
Width: 120.25
Height: 35.50
Perimeter: 311.50

Now, enter the following command in JShell to list the current, active snippets of code, loaded from the source file, that have been executed in the current session so far:

/list

The following lines show the results. Notice that JShell prefaces the different method definitions and expressions with different snippet ids because the loaded source code behaves in the same way as if we were entering one snippet after the other:

   1 : float calculateRectanglePerimeter(float width, float height) {
           float perimeter = 2 * (width + height);
           System.out.printf("Width: %.2f\n", width);
           System.out.printf("Height: %.2f\n", height);
           System.out.printf("Perimeter: %.2f\n", perimeter);
           return perimeter;
       }
   2 : float calculateRectangleArea(float width, float height) {
           float area = width * height;
           System.out.printf("Width: %.2f\n", width);
           System.out.printf("Height: %.2f\n", height);
           System.out.printf("Area: %.2f\n", area);
           return area;
       }
   3 : float width = 120.25f;
   4 : float height = 35.50f;
 
  5 : calculateRectangleArea(width, height);
   6 : calculateRectanglePerimeter(width, height);

Note

Make sure you use the previously explained /open command followed by the path and the file name for the code file that you want to load and execute in JShell whenever you find source code in the book. This way, you won't have to enter each code snippet and you will be able to check the results of executing the code in JShell.

 

Test your knowledge


  1. JShell is:

    1. A Java 9 REPL.

    2. An equivalent of javac in previous JDK versions.

    3. A Java 9 bytecode decompiler.

  2. REPL means:

    1. Run-Expand-Process-Loop.

    2. Read-Evaluate-Process-Lock.

    3. Read-Evaluate-Print-Loop.

  3. Which of the following commands lists all the variables created in the current JShell session:

    1. /variables

    2. /vars

    3. /list-all-variables

  4. Which of the following commands lists all the methods created in the current JShell session:

    1. /methods

    2. /meth

    3. /list-all-methods

  5. Which of the following commands lists the source code evaluated so far in the current JShell session:

    1. /source

    2. /list

    3. /list-source

 

Summary


In this chapter, we started our journey toward object-oriented programming with Java 9. We learned how to launch and work with the new utility introduced with Java 9 that allows us to easily run Java 9 code snippets and print its results: JShell.

We learned the necessary steps to install JDK 9 and we understood the benefits of working with a REPL. We learned to use JShell to run Java 9 code and evaluate expressions. We also learned many of its useful commands and features. We will use them in the forthcoming chapters when we will start working with object-oriented code.

Now that we have learned to work with JShell, we will learn how to recognize real-world elements and translate them into the different components of the object-oriented paradigm supported in Java 9, which is what we are going to discuss in the next chapter.

About the Author
  • Gaston C. Hillar

    Gaston C. Hillar is Italian and has been working with computers since he was 8 years old. Gaston has a Bachelor's degree in computer science (graduated with honors) and an MBA. Currently, Gaston is an independent IT consultant and a freelance author who is always looking for new adventures anywhere in the world. He was a senior contributing editor at Dr. Dobb's, and has written more than a hundred articles on software development topics. He has received the prestigious Intel Black Belt Software Developer award eight times. He has written many articles about Java for Oracle Java Magazine. Gaston was also a former Microsoft MVP in technical computing. He lives with his wife, Vanesa, and his two sons, Kevin and Brandon.

    Browse publications by this author
Latest Reviews (1 reviews total)
Although the book was OK, there was very little regarding java 9 except that the book used JShell for everything (which is pretty odd and not the purpose of JShell). Also the first couple of chapters were pretty good, but then it was like the reviewers stop and the last half of the book was pretty bad. There was ALOT of redundancy.
Java 9 with JShell
Unlock this book and the full library FREE for 7 days
Start now