Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Java 9 with JShell
Java 9 with JShell

Java 9 with JShell: Introducing the full range of Java 9's new features via JShell

eBook
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Java 9 with JShell

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.

Tip

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.

Tip

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.

Installing the required software on Windows, macOS, or Linux

Tip

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.

Tip

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.

Tip

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:

Understanding the benefits of working with a REPL

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.

Tip

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:

Checking default imports and using auto-complete features

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:

Checking default imports and using auto-complete features

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:

Checking default imports and using auto-complete features

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)

Tip

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

Tip

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:

Editing the source code in our favorite external code editor

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:

Editing the source code in our favorite external code editor

Tip

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:

Editing the source code in our favorite external code editor

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);

Tip

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.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • • A full account of Java 9’s new features
  • • This tutorial emphasises fluency using JShell exercises
  • • Get a thorough introduction to contract programming code reuse via Java generics
  • • Learn how to use the new module system
  • • How to use proper functional programming style inside Java 9

Description

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.

Who is this book for?

This book can be understood by anyone who is a graduate of computer science or someone who has just begun working as a software engineer. Basically, an understanding of an object-oriented programming language like Python, C++ or indeed, an earlier Java version is sufficient. It would be helpful to have participated in the full product cycle of a software engineering project.

What you will learn

  • • Engage with object-oriented programming in Java 9, starting with code snippets in JShell
  • • Optimize your code, applying functional programming features
  • • Discover the advantages of modularity
  • • Become very proficient at using JShell itself
  • • Learn the new approach to Java programming, which uses the REPL as a prototyping tool
Estimated delivery fee Deliver to Thailand

Standard delivery 10 - 13 business days

$8.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 29, 2017
Length: 408 pages
Edition : 1st
Language : English
ISBN-13 : 9781787282841
Vendor :
Oracle
Category :
Languages :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Estimated delivery fee Deliver to Thailand

Standard delivery 10 - 13 business days

$8.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Publication date : Mar 29, 2017
Length: 408 pages
Edition : 1st
Language : English
ISBN-13 : 9781787282841
Vendor :
Oracle
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 147.97
Java 9 Data Structures and Algorithms
$43.99
Java 9 Programming By Example
$48.99
Java 9 with JShell
$54.99
Total $ 147.97 Stars icon

Table of Contents

15 Chapters
1. JShell – A Read-Evaluate-Print-Loop for Java 9 Chevron down icon Chevron up icon
2. Real-World Objects to UML Diagrams and Java 9 via JShell Chevron down icon Chevron up icon
3. Classes and Instances Chevron down icon Chevron up icon
4. Encapsulation of Data Chevron down icon Chevron up icon
5. Mutable and Immutable Classes Chevron down icon Chevron up icon
6. Inheritance, Abstraction, Extension, and Specialization Chevron down icon Chevron up icon
7. Members Inheritance and Polymorphism Chevron down icon Chevron up icon
8. Contract Programming with Interfaces Chevron down icon Chevron up icon
9. Advanced Contract Programming with Interfaces Chevron down icon Chevron up icon
10. Maximization of Code Reuse with Generics Chevron down icon Chevron up icon
11. Advanced Generics Chevron down icon Chevron up icon
12. Object-Oriented, Functional Programming, and Lambda Expressions Chevron down icon Chevron up icon
13. Modularity in Java 9 Chevron down icon Chevron up icon
A. Exercise Answers Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
(2 Ratings)
5 star 0%
4 star 0%
3 star 50%
2 star 0%
1 star 50%
ares09x Apr 30, 2017
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Three things:1) The author seems to assume that the reader knows something about O-O languages; it's definitely not for those new to O-O.2) There are a few errors in the end-of-chapter "test your knowledge" questions.3) There's a major problem in Chapter 9 - the section called "Downcasting with interfaces and classes" is not about downcasting, it's about upcasting. When you go up a class or interface hierarchy, as the examples in this section do, from a more specific class or interface to a more general one, you are upcasting. Downcasting is treating an object that is declared as a more general type as if it were a more specific type. So, in the author's example, treating a SpiderDog object as though it were a DrawableInComic object is upcasting; treating an object declared to be of type DrawableInComic as though it were a SpiderDog object is downcasting.Note: this problem may be corrected in the paperback version, I obtained a pdf version of this book.
Amazon Verified review Amazon
Markus W. Apr 27, 2017
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
"Introducing the full range of Java 9's new features via JShell" is the subtitle of this book.More than half of the book is about basic concepts of object oriented programming. For a professional knowing his/her Java these chapters are completely useless.Neither default methods in interfaces nor generics or functional programming with lambda are new to Java 9. The new Stream methods iterate, takeWhile, dropWhile, and ofNullable to be introduced with Java 9 are not even mentioned.The pages are filled with repeated examples and how they are evaluated/displayed in JShell (pleeease, show me one or two examples, not the same five times with different values).But nonetheless learners would have a hard time with this book, too, because the author repeatedly uses concepts without introducing them properly. Ten pages with skecthes of geometric shapes shall lead you to abstraction and inheritance, without defining these concepts at this point. Base classes and interfaces are mixed chapters before they are discussed in detail. The author talks about the benefits of constructors, switches to garbage collection, and only afterwards really tells you what a constructor is.And more basic concepts (data types, variables, methods, conditions, loops) are missing completely, so no chance to learn the language with this book. Even collections appear at one point in the examples out of nowhere.Furthermore some of the presented ideas are misleading. Using immutable objects to prevent problems with concurrent programs is neither the solution to thread safe programs nor the sense of immutable objects.The description of the Jigsaw modularity system new to Java 9 lacks important features, e.g. how to integrate new code with existing one (designed for Java 8 or lower) or how to open modules for reflection, and only provides a basic idea.Even the introduction to JShell is quite basic, not a word about how to set the classpath or modulepath in JShell--which you will need to work with this tool productively.Other changes in the tooling around Java 9 or new API components are completely ignored.Of course, this is an early shot at Java 9 (and an expensive one), but neither will it present you the full range of new features nor is it an introduction for starters. Maybe programmers proficient in other languages but new to Java could benefit from the book. But even for them there will be better introductions to Java 9 soon.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela