Java Latest Version | Java 9 with Features

Java latest version and Java 9 with features

What is the Java latest version and Java 9 with features

In this blog we present a handful of recipes to help programmers Java Latest Version 9, as well as Java 9 with Features. You will learn to install Java, and also install an Integrated Development Environment (IDE) from which you’ll develop applications and experiment with the solutions provided in this blog.

 

You will learn basics of Java such as how to create a class and how to accept keyboard input. Documentation is often overlooked, but in this blog you will quickly learn how to create great documentation for your Java code.

 

Creating a Development Environment

Problem

You want to install Java and experiment with the language. You’d also like a reasonable IDE to use with it.

Solution

Install Java Development Kit 9 (JDK. That gives you the language and a compiler. Then install the NetBeans IDE to provide a more productive working environment.

Java Standard Edition (Java SE) is sufficient for most recipes in this blog. To download the release, visit the following page on the Oracle Technology Network (OTN): Java SE | Oracle Technology Network | Oracle

 

Note If you chose to only install the Java Platform (JDK) and not NetBeans, you can download NetBeans at a later time by visiting Welcome to NetBeans.

 

How It Works

The name Java™ is a trademark owned by Oracle Corporation. The language itself is open source, and its evolution is controlled by a process known as the Java Community Process (JCP). You can read more about that process at The Java Community Process(SM) Program.

 

While the language is not owned per se by Oracle Corporation, its core development tends to be steered by that company. It is Oracle Corporation that runs the JCP, and that owns the The Java Community Process(SM) Program domain.

 

There are many editions of Java, such as the Mobile Edition (ME) and the Enterprise Edition (EE). Java SE is the Standard Edition and represents the heart of the language. We’ve built the recipes in this blog for Java SE programmers. Those interested in the development of embedded applications for devices such as Raspberry Pi may be interested in learning more about Java ME. Similarly, those interested in developing web applications and working with enterprise solutions may be interested in learning more about Java EE.

 

Note Enterprise developers may want to buy and read a copy of Java EE 7

There are several good websites that you can visit to learn more about Java and keep up to date with the latest on the platform. A good place to begin for all things Java is the following page on the OTN:

 

Oracle Technology Network for Java Developers

The wealth of resources available from this page can be overwhelming at first, but it’s worth your time to look around and get passingly familiar with the many links that are available.

 

One of the links will be to Java SE, It is from there that you can download Java SE and the NetBeans IDE. Also from there you have access to the official documentation, to community resources such as forums and newsletters, and to training resources designed to help you build knowledge in Java and become certified in the language.

 

Problem

installed Java SE 9

You’ve installed Java SE 9 and the NetBeans IDE. Now you want to run a simple Java program to verify that your installation is working properly.

 

Solution

Begin by opening the NetBeans IDE. You should see a workspace resembling. You may see some projects in the left-hand pane if you’ve already been working on projects within the IDE.

 

Go to the File menu and select New Project. You’ll see the dialog. Choose the Java category, and then Java Application. Click Next to advance to the dialog. Give your project a name. For the project related to this blog, use the name Java9Recipes. Enter the project name into the Project Name text box at the top of the dialog.

 

Then specify the name of your main class in the Create Main Class text box. Give the following name:

org.java9recipes.blog01.recipe1_02.HelloWorld

 

Be sure to that you’ve entered the project name and class name just as we provide them here, because the code to follow depends upon your doing so. Make sure the “Project Name” text box specifies Java9Recipes. Make sure the “Create Main Class” text box specifies org.java9recipes.blog01. recipe1_02.HelloWorld.

 

Tip Pay attention to case, Java is case-sensitive.

 

Press “Finish” to complete the wizard and create a skeleton project. You should now be looking at a Java source file. Skeleton code is generated for you, and your NetBeans IDE window should resemble.

 

Place your cursor anywhere in the source code pane. Press Ctrl-A to select all the skeleton code. Then press Delete to get rid of it. Replace the deleted code with that from Listing 1.

 

You can find the code in Listing 1 as part of our example download for the blog. There are two files named HelloMessage.java and HelloWorld.java, which reside in a Java package named org.java9recipes.blog01. recipe1_02. Note that all recipe solutions of substance throughout this blog are in that example download.

 

The first class, HelloMessage, is a container class that is used to hold a String-based message.

Listing 1.  A “Hello, World” Example

package org.java9recipes.blog01.recipe1_02;
public class HelloMessage {
private String message = "";
public HelloMessage() {
this.message = "Default Message";
}
public void setMessage (String m) {
this.message = m;
}
public String getMessage () {
return message.toUpperCase();
}
}
The next class is named HelloWorld, and it initiates the program:
public class HelloWorld {
/* The main method begins in this class */
public static void main(String[] args) {
HelloMessage hm;
hm = new HelloMessage();
System.out.println(hm.getMessage());
hm.setMessage("Hello, World");
System.out.println(hm.getMessage());
}
}

 

Make sure you have pasted (or typed) the code from Listing 1. Compile and run the program, and you should see the following output:

run:

DEFAULT MESSAGE

HELLO, WORLD

BUILD SUCCESSFUL (total time: 1 second)

This output will appear in a new pane named “Output” that is opened by NetBeans at the bottom of the IDE window.

 

How It Works

You can run almost all the solutions in this blog using the same general technique shown in this recipe.

We’ve been painstakingly detailed for that reason, showing the step-by-step screenshots just this one time.

Java package

Packages

The solution example begins by creating a Java package:

package org.java9recipes.blog01.recipe1_02;

 

Packages are a way of grouping related classes together into a shared namespace. The idea is to achieve universal uniqueness by working your way down your organization’s domain name in reverse order. It is also customary to write package names in all lowercase.

 

NetBeans will create a directory structure to imitate your package path. In this case, NetBeans created the following directory path: C:\Users\JonathanGennick\Documents\NetBeansProjects\ Java9Recipes\class='lazy' data-src\org\java9recipes\blog01\recipe1_02

 

Following are some things to notice about this path:

The front part is C:\Users\...\NetBeansProjects. NetBeans creates all projects under a NetbeansProject directory unless you specify otherwise,  Many developers specify shorter paths. This occurrence corresponds to the project name you gave when you filled in the Project Name text box.

 

Any source files you create go into the class='lazy' data-src directory. NetBeans creates other directories at this level. For example, NetBeans creates a build directory, and then underneath it is a classes subdirectory to hold your compiled class files.

 

Last are the directories mirroring the package path that you specify, in this case org\ java9recipes\blog01\recipe1_02. When you compile your code, an identical structure is created under the build\classes directory. Note that if using another IDE, you may see differences in the directories that are created.

 

You do not need to explicitly create a package. If you do not create one, the Java compiler will create one for you, and give it a name that is hidden from you. We prefer to be explicit, and you should too. Being thoughtful and explicit about Java package names is de rigueur in the professional setting. Organization, as well as judiciously chosen naming conventions, is important when developing any significant application.

 

JavaBeans-Style Classes

JavaBeans-Style Classes

Next in the solution example you see a class definition following the JavaBeans pattern. The definition of HelloMessage follows a pattern that you’ll encounter often in Java programming, and we include it for that reason. The class is a simple one, capable of holding a single, String field named message.

 

Three methods are defined on the class:

HelloMessage(). This method, also known as the constructor, is named the same as the class. In this case, it takes no arguments. It’s automatically invoked whenever you create a new object of the class. Note that this is known as a “no-arg” constructor because it is typed out within the class, and it takes no arguments. If you do not supply a constructor, the JVM will supply a default constructor (also takes no arguments) automatically.

 

setMessage(String). This accessor method begins with the word set. It takes one parameter. It specifies the message to be returned by the corresponding get method.

getMessage(). This accessor method returns the currently defined message. In our example, we choose to uppercase the message.

 

Note Accessor methods are used in JavaBeans classes to access any privately declared class members. In this case, the private variable identified as message can be accessed using these methods. Accessor methods are more commonly referred to as “getters” and “setters.”

 

Methods beginning with set and get are termed as setter and getter methods. The variable message is private to the class, which means you have no direct access to message from outside of the class.

 

You’ll see the keyword this used in the class. It is a special keyword in Java used to reference the current object. Its use is redundant in Listing 1-1, but would be needed if any of the methods happened to create variables of their own that were also named message. It is common practice to make use of the “this” keyword to reference the class members from within the “getter” and “setter” methods.

 

It is common in Java to mediate access to class variables through setter and getter methods like those in our example. Those methods represent a contract of sorts with other classes and your main program. Their benefit is that you can change the storage implementation of HelloMessage however you like. Other code that depends upon HelloMessage will continue to work properly so long as you maintain the external behavior of setMessage() and getMessage().

 

The Main Program

Java program

The incantation public static void main(...) is used from within a public class to denote the entry point of a Java program. That declaration begins an executable method named main. You must specify one parameter that is an array of Strings, and typically that parameter is defined as String[] args.

 

When you execute the currently selected class, NetBeans compiles the code to a set of binary files, and then transfers control to the main() method. NetBeans can also be configured to recompile on save, which would then cause the transfer of control to the main() method. That method, in turn, does the following:

 

\1.\ Executes HelloMessage to create a variable named hm that is capable of holding an instance of the class HelloMessage. The variable hm is empty at this point.

 

\2.\ Invokes new HelloMessage() to create an object of the class by that name. The no-argument constructor will be executed, and "Default Message" is now set as the greeting text. The new object is now stored in the variable hm.

 

\3.\ Makes a call to System.out.println() to show that the object’s no-argument constructor has indeed executed as expected. The greeting "DEFAULT MESSAGE" is displayed in the “Output” pane.

 

\4.\ Sets the message to be the traditional text "Hello, World".

 

\5.\ Makes another call to System.out.println() to output the new message that has just been set. Now you see the greeting "HELLO, WORLD" added to the “Output” pane.

 

The pattern in the solution is common in Java programming. The main() method is where execution begins. Variables are defined, and objects are created using the new operator. Object variables are often set and retrieved using setter and getter methods.

 

Tip Command-line apps are passé. System administrators and programmers sometimes write them as utilities, or to batch-process large amounts of data. But in the main, most of today’s applications are GUI applications. 

 

Configuring the CLASSPATH

Configuring the CLASSPATH

Problem

You want to execute a Java program, or include an external Java library in the application you are executing.

 

Solution

Set the CLASSPATH variable equal to the directory location of the user-defined Java classes or Java Archive (JAR) files that you need to have access to for executing your application. Let’s say that you have a directory named JAVA_DEV located at the root of your OS drive, and all the files your applications needs to access are located in this directory. If this is the case, then you would execute a command such as the following:

set CLASSPATH=C:\JAVA_DEV\some-jar.jar

Or on Unix and Linux systems:

export CLASSPATH=/JAVA_DEV/some-jar.jar

 

Alternately, the javac command provides an option for specifying the location of resources that need to be loaded for an application. On all platforms, setting the CLASSPATH using this technique can be done via the -classpath option as follows:

javac –classpath /JAVA_DEV/some-jar.jar

Of course, on Microsoft Windows machines the file path will use the backslash (\) instead.

 

Note The javac –cp option may be used, rather than specifying the –classpath option.

 

How It Works

Java implements the concept of a classpath. This is a directory search path that you can specify system-wide using the CLASSPATH environment variable. You can also specify the classpath for a specific invocation of the JVM via the java command’s -classpath option.

 

Note The CLASSPATH is certainly going to remain important for many Java applications into the future. However, the new module system, introduced in Java 9, replaces the need to use the brittle CLASSPATH for those applications that are built to take advantage of modularization. 

 

When executing Java programs, the JVM finds and loads classes as needed using the following search order:

  • \1.\ The classes that are fundamental to the Java platform and are contained in the Java installation directory.
  • \2.\ Any packages or JAR files that are located within the extension directory of the JDK.
  • \3.\ Packages, classes, JAR files, and libraries that are loaded somewhere on the specified class path.

 

You may need to access more than one directory or JAR file for an application. This could be the case if your dependencies are located in more than one location. To do so, simply use the delimiter for your operating system (; or :) as a separator between the locations specified by the CLASSPATH variable. Following is an example of specifying multiple JAR files in the CLASSPATH environment variable on Unix and Linux systems:

 

  • export CLASSPATH=/JAVA_DEV/some-jar.jar:/JAVA_LIB/myjar.jar
  • Alternatively, you can specify the class path via a command-line option:
  • javac –classpath /JAVA_DEV/some-jar.jar:/JAVA_LIB/myjar.jar

 

When loading the resources for a Java application, the JVM loads all the classes and packages that are specified in the first location, followed by the second, and so on. This is important because the order of loading may make a difference in some instances.

 

Note JAR files are used to package applications and Java libraries into a distributable format. If you have not packaged your application in that manner, you may simply specify the directory or directories in which your .class files reside.

 

Sometimes you’ll want to include all JAR files within a specified directory. Do that by specifying the wildcard character (*) after the directory containing the files. For example:

javac –classpath /JAVA_DEV/*:/JAVA_LIB/myjar.jar

 

Specifying a wildcard will tell the JVM that it should be loading JAR files only. It will not load class files that are located in a directory specified with the wildcard character. You’ll need to specify a separate path entry for the same directory if you also want the class files. For example:

javac –classpath /JAVA_DEV/*:/JAVA_DEV

 

Subdirectories within the class path will not be searched. In order to load files that are contained within subdirectories, those subdirectories and/or files must be explicitly listed in the class path. However, Java packages that are equivalent to the subdirectory structure will be loaded. Therefore, any Java classes that reside within a Java package that is equivalent to the subdirectory structure will be loaded.

 

Note It is a good idea to organize your code; it is also good to organize where you place your code on the computer. A good practice is to place all your Java projects within the same directory; it can become your workspace. Place all the Java libraries that are contained in JAR files into the same directory for easier management.

 

Organizing Code with Packages

Organizing Code with Packages

Problem

Your application consists of a set of Java classes, interfaces, and other types. You want to organize these source files to make them easier to maintain and avoid potential class-naming conflicts.

 

Solution

Create Java packages and place source files within them much like a filing system. Java packages can be used to organize logical groups of source files within an application. Packages can help to organize code, reduce naming conflicts among different classes and other Java type files, and provide access control.

 

To create a package, simply create a directory within the root of your application source folder and name it. Packages are usually nested within each other and conform to a standard naming convention. For the purposes of this recipe, assume that the organization is named thesis and that the organization makes widgets.

 

To organize all the code for the widget application, create a group of nested packages conforming to the following directory structure:

/org/thesis

 

Any source files that are placed within a package must contain the package statement as the first line in the source. The package statement lists the name of the package in which the source file is contained. For instance, suppose that the main class for the widget application is named thesisWidgets.java.

 

To place this class into a package named org.thesis, physically move the source file into a directory named thesis, which resides within the org directory, which in turn resides within the root of the source folder for the application. The directory structure should look like the following:

/org/thesis/thesisWidgets.java
The source for thesisWidgets.java is as follows:
package org.thesis;
/**
The main class for the thesis Widgets application.
@author thesis
*/
public class thesisWidgets {
public static void main(String[] args){
System.out println("Welcome to my app!");
}
}

 

The first line in the source contains the package statement, which lists the name of the package that the source file is located within. The entire package path is listed in the statement, and the names in the path are separated by dots.

 

Note A package statement must be the first statement listed within the Java source. However, there may be a comment or Javadoc comment written before the package statement. For more information on comments or Javadoc.

 

An application can consist of any number of packages. If the widget application contains a few classes that represent widget objects, they could be placed within the org.thesis.widget package. The application may have interfaces that can be used to interact with the widget objects. In this case, a package named org. thesis.interfaces may also exist to contain any such interfaces.

 

How It Works

Java packages are useful for organizing source files, controlling access to different classes, and ensuring that there are no naming conflicts. Packages are represented by a series of physical directories on a file system, and they can contain any number of Java source files. Each source file must contain a package statement before any other statements in the file.

 

This package statement lists the name of the package in which the source file resides. In the solution to this recipe, the source included the following package statement:

 

package org.thesis;

This package statement indicates that the source file resides within a directory named thesis, and that directory resides within another directory named org. Package-naming conventions can vary by company or organization. However, it is important that words are in all lowercase so they do not conflict with any Java class file names.

 

Many companies or organizations will use the reverse of their domain name for package naming. However, if a domain name includes hyphens, underscores should be used instead.

 

Note When a class resides within a Java package, it is no longer referenced by only the class name, but instead the package name is prepended to the class name, which is known as the fully qualified name. For instance, because the class that resides within the file thesisWidgets.java is contained within the org. thesis package, the class is referenced using org.thesis.thesisWidgets, not simply thesisWidgets. An identically named class can reside within a different package (for instance, org.java9recipes. thesisWidgets).

 

Packages are very useful for establishing levels of security as well as organization. By default, different classes that reside within the same package have access to each other. If a source file resides within a different package than another file that it needs to use, an import statement must be declared at the top of the source file (underneath the package statement) to import that other file for use; otherwise, the fully qualified package.class name must be used within the code. Classes may be imported separately, as demonstrated in the following

import statement:

import org.thesis.thesisWidgets;

 

However, it is often likely that all classes and type files that reside within a package need to be used. A single import statement utilizing a wildcard character (*) can import all files within a named package as follows:

import org.thesis.*;

 

Although it is possible to import all files, it is not recommended unless absolutely necessary. As a matter of fact, it is considered a poor programming practice to include many import statements that use the wildcard. Instead, classes and type files should be imported individually.

 

Organizing classes within packages can prove to be very helpful. Suppose that the widget application that was described in the solution to this recipe includes different Java classes for each different widget object. Each of the widget classes could be grouped into a single package named org.thesis.widgets. Similarly, each of the widgets could extend some Java type or interface. All such interfaces could be organized into a package named org.thesis.interfaces.

 

Any substantial Java application will include packages. Any Java library or Application Programming Interface (API) that you use includes packages. When you import classes or types from those libraries and APIs, you are really importing packages.

 

Declaring Variables and Access Modifiers

Declaring Variables and Access Modifiers

Problem

You want to create some variables and manipulate data within your program. Furthermore, you wish to make some of the variables available to only the current class, whereas others should be available to all classes, or just the other classes within the current package.

 

Solution

Java implements eight primitive data types. There is also special support for the String class type. Listing 2 shows an example declaration of each. Draw from the example to declare the variables needed in your own application.

Declarations for Primitive and String Types package org.java9recipes.blog01.recipe1_05;
public class DeclarationsExample {
public static void main (String[] args) {
boolean BooleanVal = true; /* Default is false */
char charval = 'G'; /* Unicode UTF-16 */ Ghe(Ґ) */
charval = '\u0490'; /* Ukrainian letter
byte byteval; /* 8 bits, -127 to 127 */
short shortval; /* 16 bits, -32,768 to 32,768 */
int intval; /* 32 bits, -2147483648 to 2147483647 */
long longval; /* 64 bits, -(2^64) to 2^64 - 1 */
float floatval = 10.123456F; /* 32-bit IEEE 754 */
double doubleval = 10.12345678987654; /* 64-bit IEEE 754 */
String message = "Darken the corner where you are!"; message = message.replace("Darken", "Brighten");
}
}

 

Note If you’re curious about the Ukrainian letter in Listing 2, it is the Cyrillic letter Ghe with upturn. You can read about its history at: Ghe with upturn - Wikipedia. You can find its code point value in the chart at http://www.unicode.org/charts/PDF/U0400.pdf. And the URL http://www.unicode. org/charts/ is a good place to start whenever you need to find the code point corresponding to a given character.

 

Variables are subject to the concept of visibility. Those created in Listing 2 are visible from the main() method after they have been created, and they are deallocated when the main() method ends. They have no “life” beyond the main() method, and are not accessible from outside of main().

 

Variables created at the class level are a different story. Such variables can be termed as class fields or class members, as in fields or members of the class. Use of a member can be restricted to objects of the class in which it is declared, to the package in which it is declared, or it can be accessible from any class in any package. Listing 3 shows some of how to control visibility via the private and public keywords.

 

Listing 3.  Visibility and the Concept of Fields package org.java9recipes.blog01.recipe1_05;

class TestClass {
private long visibleOnlyInThisClass;
double visibleFromEntirePackage;
void setLong (long val) {
visibleOnlyInThisClass = val;
}
long getLong () {
return visibleOnlyInThisClass;
}
}
public class VisibilityExample {
public static void main(String[] args) {
TestClass tc = new TestClass();
tc.setLong(32768);
tc.visibleFromEntirePackage = 3.1415926535;
System.out.println(tc.getLong());
System.out.println(tc.visibleFromEntirePackage);
}
}
Output:
32768
3.1415926535

 

Members are typically bound to an object of a class. Each object of a class contains an instance of each member in the class. However, you can also define so-called static fields that occur just once, and with a single value that is shared by all instances of the given class. Listing 4 illustrates the difference.

 

Listing 4.  Static Fields

package org.java9recipes.blog01.recipe1_05;
class StaticDemo {
public static boolean oneValueForAllObjects = false;
}
public class StaticFieldsExample {
public static void main (String[] args) { StaticDemo sd1 = new StaticDemo(); StaticDemo sd2 = new StaticDemo(); System.out.println(sd1.oneValueForAllObjects);
System.out.println(sd2.oneValueForAllObjects); sd1.oneValueForAllObjects = true; System.out.println(sd1.oneValueForAllObjects); System.out.println(sd2.oneValueForAllObjects);
}
}

 

Listing 4 produces the following output:

false

false

true

true

The field oneValueForAllObjects was set to true only for the class instance named sd1. Yet it is true for instance sd2 also. This is because of the keyword static used in declaring that field. Static fields occur one time for all objects of their class.

 

How It Works

Listing 2 illustrates the basic format of a variable declaration:

type variable;

It’s common to initialize variables when declaring them, so you’ll often see:

type variable = initialValue;

Field declarations can be preceded by modifiers. For example:

public static variable = initialValue;

protected variable;

private variable;

 

It’s common to put the visibility modifier — public, protected, or private — first, but you are free to list the modifiers in any order you like. Be aware that there are additional modifiers that you will encounter and need to learn about as you get deeper into the language.

 

By default, if no modifier has been specified, the class or member is made package-private, meaning that only other classes within the package have access to the member. If a class member is specified as protected, then it is also package-private, with the exception that any subclass of its class in another package also has access.

 

The String type is special in Java. It’s really a class type, but syntactically you can treat it as a primitive type. Java automatically creates a String object whenever you enclose a String of characters within double quotes ("..."). You aren’t required to invoke a constructor, nor to specify the new keyword. Yet String is a class, and there are methods in that class that are available to you. One such method is the replace() method shown at the end of Listing 2.

 

Strings are composed of characters. Java’s char type is a two-byte construct for storing a single character in Unicode-s UTF-16 encoding. You can generate literals of the char type in two ways:

If a character is easy to type, then enclose it within single quotes (e.g.: 'G'). Otherwise, specify the four-digit UTF-16 code point value prefaced by \u (e.g.: '\u0490').

 

Some Unicode code points require five digits. These cannot be represented in a single char value.

If you are new to Java, you may be unfamiliar with the String[] array notation, as demonstrated in the examples. Please see blog 7 for more information on arrays. It covers enumerations, arrays, and also generic data types. Also in that blog are examples showing how to write iterative code to work with collections of values such as an array.

 

Compiling and Executing from the Command-Line or Terminal Interpreter

Compiling and Executing from the Command-Line

Problem

You aren’t able to install an IDE, or prefer to use a standard text editor for development. Moreover, you want to compile and execute your Java programs from the command line or terminal so that you have complete control over the environment.

Solution

Compile your programs using the javac command. Then execute them via the java command. Begin by making sure you have your JDK’s bin directory in your execution path. You might need to execute a command such as one of the following.

 

Windows:

 style="margin:0;width:982px;height:97px">setx path "%path%;C:\Program Files\Java\jdk1.9.0\bin"

OS X:

export PATH=/Library/Java/JavaVirtualMachines/jdk1.9.0.jdk/Contents/Home/bin

Then make sure your CLASSPATH environment variable includes the directory containing your Java code.

 

The following is an example of setting the environment variable under Windows:

set CLASSPATH=<<path-to-my-Java>>

 

Now change your current working directory to be the one corresponding to your project. Change to that project’s directory on a Windows system as follows:

cd <path-to-project>\Java9Recipes

Descend one level into the class='lazy' data-src subdirectory:

cd class='lazy' data-src

 

From here, you can issue javac commands to compile any classes in your project. Prepend the appropriate package name as part of your path leading to each source file to be compiled. Be sure to include the .java extension after your file name. For example, issue the following command to compile the HelloWorld class from Recipe 2.

 

Windows:

javac org\java9recipes\blog01\recipe1_02\HelloWorld.java
OS X:
javac org/java9recipes/blog01/recipe1_02/HelloWorld.java
Once the compilation is complete, you will have a .class file in the same directory as your .java file.
For example, if you perform a directory listing, you should see four files:
dir org\java9recipes\blog01\recipe1_02
HelloMessage.class
HelloWorld.class
HelloMessage.java
HelloWorld.java

Compilation produces two files. One is for HelloMessage, and the other is for the class named HelloWorld implementing the main() method.

 

Execute the main() method by issuing the java command to invoke the Java Virtual Machine (JVM). Pass the fully qualified class name as a parameter to the command. Qualify the class name by prepending the package name, but this time use the same dot-notation as used in your source file. For example: java org.java9recipes.blog1.recipe1_02.HelloWorld

Do not specify .class at the end of the command. You are referencing HelloWorld now as a class name, and not as a file name. 

 

Tip One must compile source code. Source code is kept in files with a .java suffix, so your operating system’s file and directory-path notation is appropriate. One executes a class. A class is an abstract concept in the language, so the language’s dot-notation becomes appropriate. Keep this distinction in mind to help yourself remember when to use which notation.

 

How It Works

The first two solution steps are housekeeping steps. You must have the Java compiler and the virtual machine in your execution path. It’s also necessary for any classes used by your program to be found somewhere along what is termed the classpath. One way to specify the class path is through the CLASSPATH environment variable. 

 

The command java with no c at the end is for executing compiled code. Pass as a parameter the qualified name of the class containing your main method. The JVM will interpret and execute the byte-code within that class, beginning from the main method. The JVM will search along the classpath for any additionally required classes such as HelloMessage.

 

The compiler’s default behavior is to place each generated class file into the same directory as holds the corresponding source file. You can override that behavior through the -d option. For example:

javac -d "<specify-different-location>" "<path-to-project> \Java9Recipes\class='lazy' data-src\org\java9recipes\blog1\recipe1_02\HelloWorld.java"

 

The -d option in this command designates a directory in our own environment as the target for holding generated class files. The command also specifies the full path and file name of the source file. Thus, the command can be executed with the same result regardless of the current working directory.

 

Tip Configure your system so that your command-line environment has the execution path and classpath set correctly by default. The typical approach in Linux- or Unix-based operating systems is to put appropriate commands into your .profile or .bash_profile files.

 

Under Windows you can specify environment variable defaults from the Control Panel window named System, by clicking the Advanced system settings link, and then the Environment Variables button.

 

There may be times when you need to specify a custom class path for a specific execution of the JVM.

You can do that through the -cp parameter, as follows:

java -cp ".;<path-to-project>\Java9Recipes\build\classes\org\java9recipes\blog1\ recipe1_02"

org.java9recipes.blog1.recipe1_02.HelloWorld

This execution will search first in the current working directory (the leading dot in the classpath), and then under the specified package directory corresponding to where NetBeans would place the compiled classes.

 

Developing Within the Interactive jShell

Developing Within the Interactive jShell

Problem

You wish to write Java code and have it interpreted immediately, so that you can test, prototype, and alter your code quickly, without the need to wait for compilation or the ceremony of writing an entire Java class to perform a trivial task.

 

Solution

Make use of the interactive jShell, new in Java 9, by opening a command prompt or terminal, and executing the jshell utility. The jshell is located in your JDK home bin directory, just like the java and javac utilities. Assuming that the <JDK>/bin directory is in the CLASSPATH, the jShell can be invoked using as such:

jshell

| Welcome to JShell -- Version 1.9.0

| Type /help for help

 

Once the interpreter has been started, declarations can be defined for the lifetime of the jShell session, expressions and statements can be typed and executed immediately, and so on. The jShell also allows Java developers to write a shorthand version of the language by eliminating superfluous constructs such as semicolons.

 

Listing 5 demonstrates some of the basic functionality that is provided by the jShell. Keep in mind that when you are using the interactive shell, if you at any time need assistance, you can type the /help command.

 

Listing 5.  Interactive jShell

System.out.println("Hello World")
Hello World
-> 1 + 1
| Expression value is: 2
| assigned to temporary variable $1 of type int
-> System.out.println("Hello Java 9")
Hello Java 9
-> // working with classes
-> class Main {
// Main method
public static void main(String[] args) {
System.out.println("Classes within jShell");
int index = 0;
while(index <=10){ System.out.println("Looping: " + index); index++; } } } | Added class Main -> // List classes currently loaded in jShell
-> /classes
| class Main
-> // Execute Class
-> Main.main(null)
Classes within jShell
Looping: 0
Looping: 1
Looping: 2
Looping: 3
Looping: 4
Looping: 5
-> // Reset the state of the jshell
-> /r
| Resetting state.
-> /classes
-> // Using imports
-> import java.util.ArrayList
-> import java.util.List
-> List<String> colors = new ArrayList<>(); | Added variable colors of type List<String> with initial value []
-> colors.add("red")
| Expression value is: true
| assigned to temporary variable $4 of type boolean
-> colors.add("orange")
| Expression value is: true
| assigned to temporary variable $5 of type boolean
-> colors.add("yellow")
| Expression value is: true
| assigned to temporary variable $6 of type boolean
-> colors
| Variable colors of type List<String> has value [red, orange, yellow]
-> // List the current jShell session variables -> /v
| List<String> colors = [red, orange, yellow]
| boolean $4 = true
| boolean $5 = true
| boolean $6 = true
-> // List the commands that have been executed -> /list
1 : import java.util.ArrayList;
2 : import java.util.List;
3 : List<String> colors = new ArrayList<>();
4 : colors.add("red")
5 : colors.add("orange")
6 : colors.add("yellow")
7 : colors

 

As mentioned previously, one of the boons to having an interactive shell is for prototyping code. In many cases, developers wish to prototype classes and objects. Listing 5 demonstrates how to type the code for a class into the jShell, along with some of the commands that can be useful while working with classes. When prototyping, it can oftentimes be helpful to copy code from your favorite editor and paste it into the jShell, then execute commands against it.

 

How It Works

The jShell provides a Read Evaluate Print Loop (REPL) environment for developers to type or paste in code “snippets” and have them executed immediately. Much like the REPL environments or other languages such as Groovy, Python, and JRuby, the jShell provides an excellent environment for prototyping code, and even for executing stored scripts of Java code on the fly.

 

The jShell allows one to write abbreviated Java code, otherwise known as snippets. This can be beneficial as it allows one to focus on the logic, rather than the syntax. One of the most used shortcuts is the ability to leave semicolons off the end of a line.

 

To facilitate rapid prototyping, variables can be declared outside of classes, expressions and methods can be typed on the fly outside of classes and interfaces, and expressions leave no side effects. Along with the ability to write code on the fly, the jShell provides a system that facilitates the addition, modification, and removal of code fragments within an active session or instance.

 

An active session or instance of the jShell environment constitutes a single JShellState. An instance of the JShellState includes all previously defined variables, methods, classes, import statements, and so on, that have been made within that same jShell session. Once the jShell instance is terminated, the JShellState is ended, and therefore all declarations are lost.

 

There are a number of helper commands that can be typed into the jShell to retrieve information regarding the current JShellState. The /classes command lists all of the classes that have been typed into the current JShellState. The /list command lists all of the statements, expressions, classes, methods, imports, and so on, that have been typed into the current JShellState.

 

The /list command provides a line number next to each of the listings, which enables one to easily re-execute that line of code using typing followed by the line number that you wish to re-execute.

 

Therefore, if you wish to execute line number 2 again, you would type /2 to have that line executed again. Table contains a complete listing of the commands available within jShell.

 

 jShell Commands

  • /l or /list Lists the sources typed into the current session.
  • /e or /edit [name or id of source] Opens JShell Edit Pad. Optionally type the name or id of the source entry to edit.
  • /d or /drop [name/id of source] Deletes or drops the source referenced by name or id.
  • /s or /save [all|history] Saves sources that have been typed in the current session.
  • /o or /open Opens a file of source within the jShell.
  • /v or /vars Lists variables that have been declared in the current session along with their current values.
  • /m or /methods Lists the methods that have been declared in the current session.
  • /c or /classes Lists the classes that have been declared in the current session.
  • /x or /exit Exits the current jShell session.
  • /r or /reset Resets the JShellState for the current session.
  • /f or /feedback [level] Initiates feedback- options include 
  • /p or /prompt Toggles the display of the prompt within the shell.
  • /cp or /classpath [path] Adds the typed path to the current CLASSPATH.
  • /h or /history Lists the history of the active JShellState.
  • /setstart [file] Reads and sets the startup definition file.
  • /savestart [file] Saves the current session’s definitions to the designated startup file.
  • /! Re-executes the last code snippet.
  • /<n> Re-executes the nth code snippet.

 

If you type the /e command, a scratch pad editor known as “JShell Edit Pad” will open containing the sources that you’ve entered for the current JShellState. You can edit the sources within this pad and then click the “Accept” button to have those sources evaluated within jShell.

 

Other useful features of the jShell are that you can bring up the previously typed command by pressing the up arrow on your keyboard. The interactive shell also features tab-completion. If you begin typing a statement and then press the Tab key, either the statement will be autocompleted for you or a list of options for the characters currently typed will be displayed. It is also possible to set up a predefined list of imports so that each time a jShell session is started, those imports will occur automatically.

 

The jShell provides an interactive environment that allows immediate feedback while typing code snippets. This can be beneficial for prototyping or learning the language. Other languages, such as Groovy, Python, and Scala, have similar REPL environments. Now that the jShell is available for Java, it opens the door for a more interactive environment for classroom use and increased developer prototyping productivity.

 

Tip To learn more about the commands available within the jShell, simply type /help once the shell has opened. The help feature displays an extensive listing of the features available in the jShell.

 

Converting a String

Converting a String

Problem

You have a value stored within a primitive data type, and you want to represent that value as a human-readable String. Or, you want to go in the other direction by converting a human-readable String into a primitive data type.

 

Solution

Follow one of the patterns from Listing 6. The listing shows conversion from a String to a double-precision floating-point value, and shows two methods for getting back to a String again.

 

Listing 6.  General Pattern for String Conversions

package org.java9recipes.blog01.recipe1_08;
public class StringConversion {
public static void main (String[] args) {
double pi;
String strval;
pi = Double.parseDouble("3.14"); System.out.println(strval = String.valueOf(pi)); System.out.println(Double.toString(pi));
}
}

 

How It Works

The solution illustrates some conversion patterns that work for all the primitive types. First, there is the conversion of a floating-point number from its human-readable representation into the IEEE 754 format used by the Java language for floating-point arithmetic:

pi = Double.parseDouble("3.14");

 

Notice the pattern. You can replace Double with Float, or by Long, or by whatever other type is your target data type. Each primitive type has a corresponding wrapper class by the same name but with the initial letter uppercase. The primitive type here is double, and the corresponding wrapper is Double.

 

The wrapper classes implement helper methods such as Double.parseDouble(), Long.parseLong(), Boolean. parseBoolean(), and so forth. These parse methods convert human-readable representations into values of the respective types.

 

Going the other way, it is often easiest to invoke String.valueOf(). The String class implements this method, and it is overloaded for each of the primitive data types. Alternatively, the wrapper classes also implement toString() methods that you can invoke to convert values of the underlying type into their human-readable forms. It’s your own preference as to which approach to take.

 

Conversions targeting the numeric types require some exception handling to be practical. You generally need to gracefully accommodate a case in which a character-string value is expected to be a valid numeric representation, but it’s not.  Caution Literals for the Boolean type are "true" and "false". They are case-sensitive. Any value other than these two is silently interpreted as false when converting from a String using the Boolean parseBoolean() conversion method.

 

Passing Arguments via Command-Line Execution

Passing Arguments via Command-Line Execution

Problem

You want to pass values into a Java application that is being invoked via the command line via the java utility.

 

Solution

Run the application using the java utility, and specify the arguments that you want to pass into it after the application name. If you’re passing more than one argument, each should be separated by a space. For example, suppose you want to pass the arguments to the class created in

 

Listing 7.  Example of Accessing Command-Line Arguments package org.java9recipes.blog01.recipe1_09;

public class PassingArguments {
public static void main(String[] args){
if(args.length > 0){
System.out.println("Arguments that were passed to the program: "); for (String arg:args){
System.out.println(arg);
}
} else {
System.out.println("No arguments passed to the program.");
}
}
}

 

First, make sure to compile the program so that you have a .class file to execute. You can do that from within NetBeans by right-clicking the file and choosing the “Compile File” option from the context menu, or via the javac utility at the command line or terminal.

 

Next, open a Command Prompt or terminal window and traverse into the build\classes directory for your project. For example:

cd <path-to-project>\Java9Recipes\build\classes

 

Now issue a java command to execute the class, and type some arguments on the command line following the class name. The following example passes two arguments:

java org.java9recipes.blog01.recipe1_09.PassingArguments Upper Peninsula
You should see the following output:
Arguments that were passed to the program:
Upper
Penninsula
Spaces separate arguments. Enclose Strings in double quotes when you want to pass an argument containing spaces or other special characters. For example:
java org.java9recipes.blog01.recipe1_09.PassingArguments "Upper Peninsula"
The output now shows just one argument:
Arguments that were passed to the program:
Upper Penninsula
The double quotes translate the String "Upper Peninsula" into a single argument.

 

How It Works

All Java classes that are executable from the command line or terminal contain a main() method. If you look at the signature for the main() method, you can see that it accepts a String[] argument. In other words, you can pass an array of String objects into the main() method.

 

Command-line interpreters such as the Windows Command Prompt and the various Linux and Unix shells build an array of Strings out of your command-line arguments, and pass that array to the main() method on your behalf.

 

The main() method in the example displays each argument that is passed. First, the length of the array named args is tested to see whether it is greater than zero. If it is, the method will loop through each of the arguments in the array by executing a for loop, displaying each argument along the way. If there are no arguments passed, the length of the args array will be zero, and a message indicating such will be printed. Otherwise, you see a different message followed by a list of arguments.

 

Command-line interpreters recognize spaces and sometimes other characters as delimiters. It’s generally safe to pass numeric values as arguments delimited by spaces without bothering to enclose each value within quotes. However, you should get into the habit of enclosing character-string arguments in double quotes, as shown in the final solution example. Do that to eliminate any ambiguity over where each argument begins and ends.

 

Note All arguments are seen by Java as character Strings. If you pass numeric values as parameters, they enter Java as character Strings in human-readable form. You can convert them into their appropriate numeric types using the conversion methods shown in Recipe 1-8.

 

Executing a Script via the jShell

Problem

You wish to write a prototype or script and execute it via the jShell utility from the command line or terminal.

 

Solution

While the jShell is not intended to provide a new language syntax for Java development, it is possible to save source snippets for execution within the jShell into a file, and then pass the file to the jShell utility for execution. In this solution, we’ll save a simple snippet into a file named myScript.java, and execute it with the jShell utility.

 

To get started, save the following source code into a file named myScript.java, and save it to your file system.

System.out.println("Hello from jShell")

/x

Execute the script using the following syntax:

jShell <path-to-file>/myScript.java

Output:

Hello from jShell

 

How It Works

Sometimes it can be beneficial to use a text editor or the JShell Edit Pad to save sources that can be executed within the jShell environment. This increases the ability to rapidly prototype code, and it also facilitates the ability to develop scripts that can be executed time and time again.

 

This can be useful for development of scheduled tasks or administrative tasks that can be executed by the JVM. As such, sources for the jShell can be stored into a file containing the extension of your choice, and then the file can be passed to the jShell for execution.

 

In the solution, a simple String is printed as output, and then the jShell environment is exited. Notice that the /x command is placed on a separate line after the sources within the file. The /x command tells the jShell environment to exit upon completion. If exiting upon completion, any variables, method, classes, and so on, that are defined within the file are lost once the sources have run to completion and the jShell environment is closed.

 

It is not recommended to write applications using the jShell environment for execution. In fact, GUI applications are out of scope for the jShell, and debuggers are also not supported. The environment is clearly intended for educational and prototyping purposes. However, some may find it handy to save snippets of code for execution via the jShell at a later time.

 

Accepting Input from the Keyboard

Accepting Input from the Keyboard

Problem

You are interested in writing a command-line or terminal application that will accept user input from the keyboard.

 

Solution

Make use of the ThesisScientist Domain Names.BufferedReader and ThesisScientist Domain Names.InputStreamReader classes to read keyboard entry and store it into local variables. Listing 8 shows a program that will keep prompting for input until you enter some characters that represent a valid value of type long.

 

Listing 8.  Keyboard Input and Exception Handling package org.java9recipes.blog01.recipe11;

import ThesisScientist Domain Names.*;
public class AcceptingInput {
public static void main(String[] args){ BufferedReader readIn = new BufferedReader(
new InputStreamReader(system.in -&nbspThis website is for sale! -&nbspSystem Resources and Information.)
);
String numberAsString = "";
long numberAsLong = 0;
boolean numberIsValid = false;
do {
/* Ask the user for a number. */ System.out.println("Please enter a number: "); try {
numberAsString = readIn.readLine(); System.out.println("You entered " + numberAsString);
} catch (IOException ex){ System.out.println(ex);
}
/* Convert the number into binary form. */
try {
numberAsLong = Long.parseLong(numberAsString); numberIsValid = true;
} catch (NumberFormatException nfe) { System.out.println ("Not a number!");
}
} while (numberIsValid == false);
}
}
Following is an example run of this program:
Please enter a number:
No
You entered No
Not a number!
Please enter a number:
Yes
You entered Yes
Not a number!
Please enter a number:
42
You entered 42

 

BUILD SUCCESSFUL (total time: 11 seconds)

The first two inputs did not represent valid values in the long data type. The third value was valid, and the run ended.

 

How It Works

Quite often our applications need to accept user input of some kind. Granted, most applications are not used from the command line or terminal nowadays, but having the ability to create an application that reads input from the command line or terminal helps to lay a good foundation, and may be useful in some applications or scripts. Terminal input can also be useful in developing administrative applications that you or a system administrator may use.

 

Two helper classes were used in the solution to this recipe. They are ThesisScientist Domain Names.BufferedReader and ThesisScientist Domain Names.InputStreamReader. The early portion of the code that’s using those classes is especially important to understand:

 BufferedReader readIn = new BufferedReader(

new InputStreamReader(system.in -&nbspThis website is for sale! -&nbspSystem Resources and Information.)

);

 

The innermost object in this statement is system.in -&nbspThis website is for sale! -&nbspSystem Resources and Information.. It represents the keyboard. You do not need to declare system.in -&nbspThis website is for sale! -&nbspSystem Resources and Information.. Java’s runtime environment creates the object for you. It is simply available to be used.

 

system.in -&nbspThis website is for sale! -&nbspSystem Resources and Information. provides access to raw bytes of data from the input device, which is the keyboard in our example. It is the job of the InputStreamReader class to take those bytes and convert them into characters in your current character set. system.in -&nbspThis website is for sale! -&nbspSystem Resources and Information. is passed to the InputStreamReader() constructor to create an InputStreamReader object.

 

InputStreamReader knows about characters, but not about lines. It is the BufferedReader class’s job to detect line breaks in the input stream, and to enable you to conveniently read a line at a time. BufferedReader also aids efficiency by allowing physical reads from the input device to be done in different-size chunks than by which your application consumes the data. This aspect can make a difference when the input stream is a large file rather than the keyboard.

 

Following is how the program in Listing 8 makes use of an instance (named readIn) of the BufferedReader class to read a line of input from the keyboard:

numberAsString = readIn.readLine();

 

Executing this statement triggers the following sequence:

  • \1.\ system.in -&nbspThis website is for sale! -&nbspSystem Resources and Information. returns a sequence of bytes.
  • \2.\ InputStreamReader converts those bytes into characters.
  • \3.\ BufferedReader breaks the character stream into lines of input.
  • \4.\ readLine() returns one line of input to the application.

 

I/O calls must be wrapped in try-catch blocks. These blocks are used to catch any exceptions that may occur. The try part in the example will fail in the event a conversion is unsuccessful. A failure prevents the numberIsValid flag from being set to true, which causes the do loop to make another iteration so that the user can try again at entering a valid value. To learn more about catching exceptions, please see blog 9.

 

The following statement at the top of Listing 8 deserves some mention:

import ThesisScientist Domain Names.*;

 

This statement makes available the classes and methods defined in the ThesisScientist Domain Names package. These include InputStreamReader and BufferedReader. Also included is the IOException class used in the first try-catch block.

 

Documenting Your Code

Documenting Your Code

Problem

You want to document some of your Java classes to assist in future maintenance.

 

Solution

Use Javadoc to place comments before any class, method, or field that you want to document. To begin such a comment, write the characters /**. Then begin each subsequent line with an asterisk (*). Lastly, close the comment with the characters */ on a line by themselves at the end. Listing 9 shows a method commented with Javadoc.

 

Listing 9.  Comments Made in Javadoc Form package org.java9recipes.blog01.recipe1_12;

import java.math.BigInteger;
public class JavadocExample {
/**
Accepts an unlimited number of values and
returns the sum.
*
@param nums Must be an array of BigInteger values.
@return Sum of all numbers in the array.
*/
public static BigInteger addNumbers(BigInteger[] nums) { BigInteger result = new BigInteger("0");
for (BigInteger num:nums){
result = result.add(num);
}
return result;
}
/**
Test the addNumbers method.
@param args not used
*/
public static void main (String[] args) {
BigInteger[] someValues = {BigInteger.TEN, BigInteger.ONE}; System.out.println(addNumbers(someValues));
}
}

Comments can be added to the beginning of classes and fields in the same way. The comments are helpful to you and other programmers maintaining the code, and their specific format enables easy generation of an HTML reference to your code.

 

Generate the HTML reference by invoking the tool named Javadoc. This is a command-line tool that parses a named Java source file and formulates HTML documentation based upon the defined class elements and Javadoc comments. For example:

 

javadoc JavadocExample.java

This command will produce several HTML files containing the documentation for the class, methods, and fields. If no Javadoc comments exist within the source, some default documentation will still be produced. To view the documentation, load the following file into your browser:

 

index.html

The file will be in the same directory as the class or package that you are documenting. There will also be an index-all.html file giving a strict alphabetical listing of documented entities.

Keep in mind that the same rules apply when using the Javadoc tool as when using javac. You must reside within the same directory as the source file, or prepend the name of the file with the path to where the file is located.

 

How It Works

Generating documentation for applications from scratch can be quite tedious. Maintaining documentation can be even more troublesome. The JDK comes packaged with an extensive system for documentation known as Javadoc. Placing some special comments throughout your code source and running a simple command-line tool makes it easy to generate useful documentation and keep it current. Moreover, even

 

if some of the classes, methods, or fields in an application are not commented specifically for the Javadoc utility, default documentation will still be produced for such elements.

 

Formatting the Documentation

Formatting the Documentation

To create a Javadoc comment, begin with the characters /**. Although optional since Java 1.4, a common practice is to include an asterisk as the first character of every subsequent line within the comment. Another good practice is to indent the comment so that it aligns with the code that is being documented. Lastly, close the comment with the characters */.

 

Javadoc comments should begin with a short description of the class or method. Fields are rarely commented using Javadoc, unless they are declared public static final (constants), in which case it is a good idea to supply a comment. A comment can be several lines in length, and can even contain more than one paragraph.

 

If you want to break comments into paragraphs, then separate those paragraphs using the <p> tag. Comments can include several tags that indicate various details regarding the method or class that is being commented. Javadoc tags begin with an ampersand (@), and some of the common tags are as follows:

@param: Name and description of a parameter

@return: What is returned from the method

@see: Reference to another piece of code

 

You may also include inline links within Javadoc to reference URLs. To include an inline link, use the tag {@link My Link}, where link is the actual URL that you want to point at and My Link is the text that you want to have appear. There are also many other tags that can be used within Javadoc comments, including {@literal}, {@code}, {@value org}, and many others. For a complete listing, see the Javadoc reference on the OTN website.

 

Executing the Tool

The Javadoc tool can also be run against entire packages or source. Simply pass a package name to the Javadoc tool rather than individual source file names. For instance, if an application includes a package named org.thesis.beans, all source files within that package can be documented by running the tool as follows:

javadoc org.thesis.beans

 

To generate Javadoc for more than one package at a time, separate the package names with spaces as follows:

javadoc org.thesis.beans org.thesis.entity

Another option is to specify the path to the source files using the –sourcepath flag. For example:

javadoc –sourcepath /java/class='lazy' data-src

 

By default, the Javadoc tool will generate HTML and place it into the same package as the code being documented. That result can become a cluttered nightmare if you like to have source files separate from documentation. You can instead set up a destination for the generated documentation by passing the –d flag to the Javadoc tool.

 

 Reading Environment Variables

Reading Environment Variables

Problem

The application you are developing needs to make use of some environment variables. You want to read the values that have been set from the operating-system level.

 

Solution

Make use of the Java System class to retrieve any environment variable values. The System class has a method called getenv(), which accepts a String argument corresponding to the name of a system environment variable. The method will then return the value of the given variable. If no matching environment variable exists, a NULL value will be returned.

 

Listing 10 provides an example. The class ReadOneEnvVariable accepts an environment variable name as a parameter, and displays the variable’s value that has been set at the operating-system level.

 

Listing 10.  Reading an Environment Variable’s Value package org.java9recipes.blog1.recipe1_13;

public class ReadOneEnvVariable {
public static void main(String[] args) {
if (args.length > 0) {
String value = System.getenv(args[0]);
if (value != null) {
System.out.println(args[0].toUpperCase() + " = " + value); } else {
System.out.println("No such environment variable exists");
}
} else {
System.out.println("No arguments passed");
}
}
}

 

If you are interested in retrieving the entire list of environment variables that is defined on a system, do not pass any arguments to the System.getenv() method. You’ll receive back an object of type Map having all the values. You can iterate through them as shown in Listing 11.

 

Listing 11.  Iterating Through a Map of Environment Variables package org.java9recipes.blog1.recipe13;

import java.util.Map;
public class ReadAllEnvVariables {
public static void main(String[] args){
if(args.length > 0){
String value = System.getenv(args[0]);
if (value != null) {
System.out.println(args[0].toUpperCase() + " = " + value);
} else {
System.out.println("No such environment variable exists");
}
} else {
Map<String, String> vars = System.getenv();
for(String var : vars.keySet()){
System.out.println(var + " = " + vars.get(var));
}
}
}
}

How It Works

The System class contains many different utilities that can aid in application development. One of those is the getenv() method, which will return a value for a given system environment variable.You can also return the values from all variables, in which case those values are stored in a map. A map is a collection of name/value pairs. 

 

The method invoked to obtain environment variable values in Listings 10 and 11 is the same. It’s been overloaded to handle both cases shown in the solution. Pass the name of a variable as a String if you want to obtain just that variable’s value. Pass no argument at all to get back the names and values of all variables that are currently set.

 

Java 9 Enhancements

Java 9 Enhancements

Each release of the JDK brings forth new enhancements and capability to the Java platform. Each release also carries with it backward compatibility with previous releases. This blog includes a number of recipes covering the new features for Java 9, and this blog showcases a few of the top enhancements to whet your appetite.

 

By no means is this blog a complete listing of all Java 9 enhancements. Rather, it is a jump start to get you going on some of the hot new features of Java 9.

 

Avoiding Redundancy in Interface Code

Problem

You would like to implement two or more default methods within an interface that will contain very similar code. Rather than copying code into each of the different default methods and maintaining each default method separately, you’d like to encapsulate the similar code into its own method for reuse.

 

Solution

Make use of a private method in an interface to alleviate this issue. Java 9 provides the ability to include private methods within an interface. A private method is only available within that interface, and it cannot be used by any class that implements the interface. However, each default method implementation that is part of the interface can make use of the private method.

The following interface includes two default methods and one private method. The private method encapsulates functionality that can then be used in each of the default method implementations.

public interface Pool {
/**
Calculate volume (gal) for a fixed depth square or rectangular pool.
*/
public default double squareOrRectConstantDepth(double length, double width, double depth){
return volumeCalc(length, width, depth);
}
/**
Calculate volume (gal) for a variable depth square or rectangular pool.
*/
public default double squareOrRectVariableDepth(double length, double width,
double shallowDepth, double middleDepth,
double deepDepth){
double avgDepth = (shallowDepth + middleDepth + deepDepth) / 3;
return volumeCalc(length, width, avgDepth);
}
/**
Standard square or rectangular volume calculation.
*/
private double volumeCalc(double length, double width, double depth){ return length * width * depth * 7.5;
}
}

 

How It Works

Prior to Java 8, it was not possible to include code implementation within a Java interface. An interface is a reference type in Java, similar to a class. However, its original intent only allowed abstract methods, constants, static methods, and nested types. Therefore, classes that implemented an interface must implement each of the abstract methods. In Java 8, that restriction was lifted, and it became possible to include method implementations in the form of default methods.

 

A default method can contain an implementation in the interface, or its implementation could be overridden by an implementing class. Hence, the name default method, meaning that the default method implementation resides in the interface if one is not provided by the implementation class. Private methods were not allowed in interfaces.

 

Situations have arisen by which multiple default methods within an interface may contain similar code. This code can now be encapsulated within a private method implementation within the interface. The private method implementation cannot be used outside of the interface. It can only be used by any default methods contained within the same interface.

 

In the solution to this recipe, the volumeCalc() method returns the calculated volume of a square or rectangular swimming pool using a standard formula. Each of the default methods within the interface are able to utilize the volumeCalc() method to find the volume. However, the volumeCalc() method will not be available for use outside of the interface.

 

This seems to be a controversial topic, as interfaces were originally intended for field and method declarations only, but it can also be argued that copying the same code throughout a number of default method implementations would be a bad practice. Take it as you will, this feature makes it easier to reuse code within an interface, thereby reducing the chance for errors and making maintenance much easier.

 

Creating Modules for Simplifying and Code Reuse

Creating Modules for Simplifying and Code Reuse

Problem

You are writing a utility library or a Java application, and you do not wish to rely upon the classpath to manage dependencies with other libraries. Furthermore, you wish to package your library such that it can easily be integrated into other projects.

 

Solution

Develop your library or application as a module. Creation of modules is quite easy. However, modules can themselves become quite complex. This example will cover the creation of a very simple module that does not depend upon any other modules. No other modules will depend upon the module either. Begin by creating a new directory somewhere on your file system…in this case name it “recipe2.”

 

Create a new folder named class='lazy' data-src within it, and then create a file named module-info.java, which is the module descriptor, within the class='lazy' data-src folder. In this file, list the

module name as follows:

module org.acme {}

 

Next, create a folder named org.acme.wordcount within the class='lazy' data-src directory that was created previously. Next, create a folder named org within the org.acme.wordcount folder. Subsequently, create an acme folder within the org folder, followed by a wordcount folder within the acme folder.

 

Now, create the bulk of the module by adding a new file named WordCount.java inside of the wordcount folder. Place the following code within the WordCount.java file:

package org.acme.wordcount;
public class WordCount {
public static void main(String[] args) {
int counter = 0;
if (args.length > 0){
for(String arg:args){
System.out.println("Position " + counter + ": " + arg.length()); counter++;
}
}
}
}

Make use of the javac utility to compile the module by using the command line or terminal and traversing inside of the class='lazy' data-src directory you created earlier. Issue the javac command, specifying the -d flag to list the folder into which the compiled code will be placed. List each of the source files to be compiled, including the module-info.java descriptor, separating each with a space.

 

The following command compiles the sources that were developed in and places the result into a directory named mods/org.acme.wordcount.

javac -d class='lazy' data-src/mods/org.acme.wordcount class='lazy' data-src/module-info.java class='lazy' data-src/org.acme.wordcount/org/acme/ wordcount/WordCount.java

 

Now that the code has been compiled, it is time to execute the module. Use the java executable, specifying the --module-path option, which is new in Java 9, to indicate the path of the module sources. The -m option is used to specify the Main class of the module. Traverse inside of the class='lazy' data-src directory and issue the following:

java --module-path mods -m org.acme.wordcount/org.acme.wordcount.WordCount testing one two three

 

This example passes the words “testing,” “one,” “two,” “three” to the module to be counted. The output should look as follows:

Position 0: 7

Position 1: 3

Position 2: 3

Position 3: 5

 

How It Works

Project Jigsaw brought modules into fruition for the Java platform, finally introducing a means to do away with the classpath of the old, and make use of a newer, more pluggable architecture. The Java 9 module system allows one to package self contained modules of code and make them versatile such that a module can be made to depend upon other modules, or on the other hand, other modules can be made to depend upon it.

 

This modular dependency takes place of the old classpath system, although the classpath is still available for use to accommodate backward compatibility and also for cases where modularity makes little sense.

 

Creation of a module consists of a module-info.java descriptor file. This file is used to indicate the package containing the module, as well as the dependency contracts that the module shares with other modules. 

 

The self-contained application in this recipe resides within the org.acme.wordcount.WordCount.java file, and it can be compiled with javac, and executed with the java executable, as one would imagine. These two utilities have new options available to support modularity, and the recipe demonstrates the use of these new options for compiling and executing the module. 

 

Easily Retrieving Information on OS Processes

updated Process API in Java 9

Problem

You would like the ability to find information regarding operating system processes.

 

Solution

Make use of the updated Process API in Java 9. The new ProcessHandle interface allows one to easily obtain information regarding operating system processes. In the following code, all operating system processes are listed and printed to the command line.

public static void listProcesses(){

ProcessHandle.allProcesses()

.forEach(System.out::println);

}

However, this is not very helpful, as it simply lists the process number of each operating system process…which is not very useful. To obtain more detail on the process, we need to obtain the ProcessHandle and call upon its helper methods, which is quite easy to do. The following code will print much more information regarding each process, as it prints the http://ProcessHandle.Info itself.

public static void detailListProcesses(){
ProcessHandle.allProcesses()
.forEach(h->System.out.println(formattedProcess(h)));
}
public static String formattedProcess(ProcessHandle handle){ long pid = handle.getPid();
boolean alive = handle.isAlive();
Optional<Duration> cpuDuration = http://handle.info().totalCpuDuration(); Optional<String> handleName = http://handle.info().command();
return pid + " " + alive + " " + handleName + ":"+ cpuDuration;
}
Sample output may look as follows:
17584 true Optional[/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/bin/ java]:Optional[PT0.250501S]
17581 true Optional[/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/bin/ java]:Optional.empty
17576 true Optional.empty:Optional.empty
17575 true Optional.empty:Optional.empty
17574 true Optional.empty:Optional.empty
17364 true Optional[/System/Library/Frameworks/CoreServices.framework/Frameworks/Metadata. framework/Versions/A/Support/mdworker]:Optional.empty
17247 true Optional[/Applications/Google Chrome.app/Contents/Versions/56.0.2924.87/Google Chrome Helper.app/Contents/MacOS/Google Chrome Helper]:Optional.empty

 

If you wish to retrieve information pertaining to the user that is running the process, that is easy to do as well.

public static void detailListProcessUsers(){
ProcessHandle.allProcesses()
.forEach(h->System.out.println(listOsUser(h)));
}
public static String listOsUser(ProcessHandle handle){ http://ProcessHandle.Info procInfo = http://handle.info(); return handle.getPid() + ": " +procInfo.user();
}
Sample output using this technique may look as follows:
17584: Optional[thesis]
17581: Optional[thesis]
17576: Optional[_postfix]
17575: Optional[_postfix]
17574: Optional[root]

 

How It Works

Prior to the release of Java 9, it was cumbersome to obtain information regarding operating system processes. We had to obtain process IDs using the ManagementFactory.getRuntimeMXBean() method and then parse the String that was returned. The ProcessHandle interface is introduced in Java 9, making the retrieval of operating system process information a first class citizen of the JDK. BelowTable shows the methods that can be called upon within ProcessInfo in order to retrieve the desired information.

 

ProcessHandle Interface

Method Description

  • allProcesses() Snapshot of all processes that are visible to the current process.
  • children() Snapshot of the children of the current process.
  • compareTo(ProcessHandle) Compare one ProcessHandle to another.
  • current() Returns the ProcessHandle for the current process.
  • descendants() Snapshot of all descendants of the current process.
  • destroy() Requests the process to be killed. Returns a boolean to indicate result.
  • destroyForcibly() Requests the process to be killed forcibly. Returns a boolean to indicate result.
  • equals(Object) Returns a true if the object passed in is not null, and represents the same system process, otherwise returns a false.
  • getPid() Returns the process ID for the process.
  • hashCode() Returns hash code value for the process.

 

Handling Errors with Ease

Handling Errors with Ease

Problem

You’d like to easily manage the closing of effectively final variables.

 

Solution

The try-with-resources construct was introduced in Java 7, and it allows for easy management of resources. In Java 9, it became even easier as there is no need to effectively create a new variable for the sake of the construct. In the following code, the writeFile() method takes a BufferedWriter as an argument, and since it is passed into the method and ready to use, it is effectively final. This means that it can simply be listed in the try-with-resources, rather than creating a new variable.

public static void main(String[] args) {
try {
writeFile(new BufferedWriter(
new FileWriter("Easy TryWithResources")),
"This is easy in Java 9");
} catch (IOException ioe) { System.out.println(ioe);
}
}
public static void writeFile(BufferedWriter writer, String text) { try (writer) {
writer.write(text);
} catch (IOException ioe) { System.out.println(ioe);
}
}
Prior to Java 9, the writeFile would have looked as follows:
public static void writeFile(BufferedWriter writer, String text) { try (BufferedWriter w = writer) {
w.write(text);
} catch (IOException ioe) { System.out.println(ioe);
}
}

This code will create a new file named “Easy TryWithResources” and it will put the text “This is easy in Java 9” into the file.

 

How It Works

The try-with-resources construct has become even easier with Java 9. The try-with-resources construct was introduced in Java 8, which allows one to handle the opening and closing of resources very easily. If we have a resource, such as a database Connection or a BufferedStream, it is a good idea to manage wisely.

 

In other words, open the resource, then use it accordingly, and finally close the resource when finished to ensure that there are no resource leaks. The try-with-resources construct allows one to open a resource within the try block and have it automatically cleaned up once the block completes.

 

In the solution, the original way to handle resources is shown, followed by the new way in Java 9. It is now possible to simply begin making use of a resource within a try-with-resources construct if it is passed into a method as an argument or if it is a final field. This means that is no longer necessary to create a placeholder variable for the purposes of utilization within the try-with-resources.

 

While this is not a major language change, it will certainly make handling resources a bit easier, and it certainly makes the try-with-resources block even easier to understand.

 

Filtering Data Before and After a Condition with Streams

Problem

You wish to utilize streams for effective manipulation of your collections. While doing so, you wish to filter those streams before and/or after a specified condition occurs. In the end, you want to retrieve all data within the collection before a given predicate condition is met. You also wish to retrieve all data within the collection that is placed after a given predicate condition is met.

 

Solution

Utilize the new Java 9 takeWhile() and dropWhile() constructs with your stream. Suppose we have the following collection of data, and we wish to retrieve all of the elements prior to the element containing the word “Java.”

List<String> myLangs = Arrays.asList("Jython is great","Groovy is awesome", "Scala is functional", "JRuby is productive","Java is streamlined","","Kotlin is interesting");

 

To retrieve all elements prior to the element containing the String “Java”, we could use the takeWhile() construct, as follows:

Stream.of("Jython is great","Groovy is awesome","Scala is functional",

"JRuby is productive","Java is streamlined","","Kotlin is interesting")

.takeWhile(s -> !s.contains("Java"))

.forEach(System.out::println);

 

Let’s suppose that we wish to retrieve all elements that occur after the element containing the String “Java”. We could use the dropWhile() construct, as follows:

Stream.of("Jython is great","Groovy is awesome","Scala is functional",

"JRuby is productive","Java is streamlined","","Kotlin is interesting")

.dropWhile(s -> !s.contains("Java"))

.forEach(System.out::println);

 

How It Works

Streams changed the way that we develop code and handle collections of data in Java. The original set of filters that were available for use with streams was fairly generous. However, in Java 8, even more options have been added, making it even easier to refine data with streams.

 

The takeWhile() and dropWhile() constructs allow streams to be parsed, returning a new stream that contains all elements before the first one that fails the specified predicate condition, or returning a new stream containing all elements including and after the first element that fails a specified predicate, respectively.

 

In the solution to this recipe, the list of Strings is parsed, printing each of the elements to the command line for the first pass. The takeWhile() construct is then applied to the same stream of Strings and the elements from the stream before the element that fails the specified condition will be printed to the command line.

 

The takeWhile() accepts a predicate condition, which it then applies to each of the elements in the stream, and then only those elements that are iterated before the predicate condition is not matched will be returned. All elements that reside in the stream at and after the position where the condition is not met will not be returned.

 

The opposite result occurs when using the dropWhile() construct. In the solution, all stream elements will be ignored up until the first element upon which the specified condition is no longer met will be returned. Each subsequent element in the stream will also be returned. The takeWhile and dropWhile constructs are very similar to the filter, with the exception that only one failed condition will cause the remaining elements to be ignored or returned, respectively.

 

Developing a Concise HTTP Client

Developing a Concise HTTP Client

Problem

You wish to develop an HTTP client within a Java application.

HttpResponse r1;
try {
r1 = HttpRequest.create(new URI("thesis"))
.GET()
.response();
int responseCode = r1.statusCode();
if(responseCode == 200){
System.out.println(r1.body(asString()));
}
} catch (URISyntaxException|IOException|InterruptedException ex) {
Log error
}

 

Solution

Make use of the updated HTTP/2 client for Java 9. In the following example, the thesis website is parsed and returned via HTTP client code. In the following example, the thesis web page for US is returned as a String.

 

The output will look something like the following (abbreviated for brevity):

<!DOCTYPE html>
<!--[if lt IE 7]> <html lang=en class="no-js ie6 lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 7]> <html lang=en class="no-js ie7 lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html lang=en class="no-js ie8 lt-ie9"> <![endif]--> <!--[if IE 9]> <html lang=en class="no-js ie9"> <![endif]-->
<!--[if gt IE 9]><!--> <html lang=en class=no-js> <!--<![endif]--> <head><meta http-equiv=x-ua-compatible content="IE=edge">
<script type=text/javascript class='lazy' data-src="//static.Thesis.com/spcom/js/vendor/googleapis/ajax/ libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript class='lazy' data-src=//cdn.optimizely.com/js/8200882355.js></script> <script type=text/javascript id=angular-script class='lazy' data-src="//static.Thesis.com/spcom/js/ vendor/googleapis/ajax/libs/angularjs/1.2.17/angular.min.js"></script>
<script type=text/javascript id=script--1908162026 class='lazy' data-src="//static.Thesis.com/spcom/min/ prod.js?r=201702071421-9"></script>
<link rel=stylesheet type=text/css href="//static.Thesis.com/spcom/min/modern_sprcom-cms-frontend_thesis.css?r=201702071421-9" />
<!--[if (lt IE 9) & (!IEMobile)]><link rel=stylesheet type=text/css href="//static. http://thesisscientist.com" media=screen /><![endif]-->
<link rel=stylesheet type=text/css href="//static.Thesis.com/spcom/min/print. css?r=201702071421-9" media=print />
<link rel=stylesheet type=text/css href="/spcom/css/vendor/font-awesome.min. css?r=201702071421-9" />
<!--[if lt IE 9]><script type=text/javascript id=ielt9js charset=utf-8 class='lazy' data-src=//static.http://thesisscientist.com></script>

 

Note This is an excellent example to try out in the Java 9 jShell utility. To start the utility, open a command prompt or terminal and type jshell –add-modules java.httpclient to start the shell including the httpclient module. This assumes that the jshell executable utility resides within the PATH.

 

How It Works

The new javax.httpclient module has been added to Java 9, and it comprises of high level HTTP and WebSocket client APIs. The API provides synchronous and asynchronous implementations for the HTTP Client, and asynchronous implementations for WebSocket. The API resides within the http://java.net.http package.

 

The HttpClient is a container for configuration information that is common to the HttpRequests type. An HttpClient is generated by initiating an HttpRequest.Builder, passing the URI for the request, and then calling upon the create() method. The create() method returns an immutable HttpClient.

 

As seen in the solution to this recipe, the client can be used to perform a number of activities, both synchronously and asynchronously. Asynchronous requests will return a CompleteableFuture object for use. For more details regarding the HTTP and WebSocket clients.

 

Utilizing Factory Methods to Create Immutable Collections

 

Problem

You wish to generate an immutable Collection of values

Solution

Utilize the Collection.of() construct to generate an immutable collection. In the following example, two Collections are created. The first is an immutable List<String>, and the second is an immutable

Map<Integer, String>.
List<String> jvmLanguages = List.of("Java", "Scala", "JRuby", "Groovy", "Jython", "Kotlin");
System.out.println(jvmLanguages);
try {
jvmLanguages.add("Exception");
} catch (UnsupportedOperationException uoe){ System.out.println(uoe);
}
Map <Integer, String> players = Map.of(1, "thesisthesis", 2, "Jonathan Gennick", 3, "Freddy Guime", 4, "Carl Dea");
System.out.println(players.values()); System.out.println("Player 2: " + players.get(2));
The output would look like the following. Note that in the example I have added a try-catch block to catch the UnsupportedOperationException that is thrown when I attempt to modify the List.
[Java, Scala, JRuby, Groovy, Jython, Kotlin]
java.lang.UnsupportedOperationException
[Carl Dea, Jonathan Gennick, Freddy Guime, thesisthesis] Player 2: Jonathan Gennick

 

How It Works

Java has historically been a verbose language for performing small tasks. In the past, constructing a populated Collection of data took a few lines of code. On the first line, the Collection must be initialized, followed by a line of code for each item that was added to it. Java 9 adds the convenient API for quickly producing an unmodifiable Collection of data, whereby one can now initialize and populate the construct in one line of code.

 

Factory methods have been added to the List, Set, and Map interfaces for creating such unmodifiable collections of data. The factory methods consist of the of() method, which accepts up to ten values, for quickly creating an immutable collection. The Map factory method accepts up to ten key/value pairs.

 

If more than ten pairs is needed for the Map, then it is possible to call upon the Map.ofEntries() method, passing an arbitrary number of Map.Entry<k,v>. Furthermore, no null values can be used to populate as elements, keys, or values.

 

Summary

This blog covered a handful of the new features and enhancements that have been added to Java 9. While certainly not a complete listing of new features, this blog delved into a few of the most anticipated features, including modularity, Process API, and easy error handling. To gain a more complete knowledge of new features, the entire blog should be read through. However, this blog gave you a taste for what is to come.