Development Basics - Platform - Java 8 Pocket Guide (2014)

Java 8 Pocket Guide (2014)

Part II. Platform

Chapter 10. Development Basics

The Java Runtime Environment (JRE) provides the backbone for running Java applications. The Java Development Kit (JDK) provides all of the components and necessary resources to develop Java applications.

Java Runtime Environment

The JRE is a collection of software that allows a computer system to run a Java application. The software collection consists of the Java Virtual Machines (JVMs) that interpret Java bytecode into machine code, standard class libraries, user interface toolkits, and a variety of utilities.

Java Development Kit

The JDK is a programming environment for compiling, debugging, and running Java applications, Java Beans, and Java applets. The JDK includes the JRE with the addition of the Java programming language and additional development tools and tool APIs. Oracle’s JDK supports Mac OS X, Solaris, Linux (Oracle, Suse, Red Hat, Ubuntu, and Debian [on ARM]), and Microsoft Windows (Server 2008 R2, Server 2012, Vista, Windows 7, and Windows 8). Additional operating system and special purpose JVMs, JDKs, and JREs are freely available from Java Virtual Machine. Supported browsers are Internet Explorer 9+, Mozilla Firefox, Chrome on Windows, and Safari 5.x.

Table 10-1 lists versions of the JDK provided by Oracle. Download the most recent version at Oracle’s website, where you can also download older versions.

Table 10-1. Java Development Kits

Java Development Kits

Codename

Release

Packages

Classes

Java SE 8 with JDK 1.8.0

---

2014

217

4,240

Java SE 7 with JDK 1.7.0

Dolphin

2011

209

4,024

Java SE 6 with JDK 1.6.0

Mustang

2006

203

3,793

Java 2 SE 5.0 with JDK 1.5.0

Tiger

2004

166

3,279

Java 2 SE with SDK 1.4.0

Merlin

2002

135

2,991

Java 2 SE with SDK 1.3

Kestrel

2000

76

1,842

Java 2 with SDK 1.2

Playground

1998

59

1,520

Development Kit 1.1

---

1997

23

504

Development Kit 1.0

Oak

1996

8

212

Java SE version 6 reached Oracle’s End of Public Updates in March 2013.

Java Program Structure

Java source files are created with text editors such as jEdit, TextPad, Vim, Notepad++, or one provided by a Java Integrated Development Environment (IDE). The source files must have the .java extension and the same name as the public class name contained in the file. If the class haspackage-private access, the class name can differ from the filename.

Therefore, a source file named HelloWorld.java would correspond to the public class named HelloWorld, as represented in the following example (all nomenclature in Java is case-sensitive):

1 package com.oreilly.tutorial;

2 import java.time.*;

3 // import java.time.ZoneId;;

4 // import java.time.Clock;

5

6 public class HelloWorld

7 {

8 public static void main(String[] args)

9 {

10 ZoneId zi = ZoneId.systemDefault();

11 Clock c = Clock.system(zi);

12 System.out.print("From: "

13 + c.getZone().getId());

13 System.out.println(", \"Hello, World!\"");

14 }

15 }

In line 1, the class HelloWorld is contained in the package com.oreilly.tutorial. This package name implies that com/oreilly/tutorial is a directory structure that is accessible on the class path for the compiler and the runtime environment. Packaging source files is optional, but is recommended to avoid conflicts with other software packages.

In line 2, the import declaration allows the JVM to search for classes from other packages. Here, the asterisk all classes in the java.time package available. However, you should always explicitly include classes so that dependencies are documented, including the statements import java.time. ZoneId; and import java.time.Clock;, which as you see are currently commented out and would have been a better choice than simply using import java.time.\*;. Note that import statements are not needed because you can include the full package name before each class name; however, this is not an ideal way to code.

TIP

The java.lang package is the only Java package imported by default.

In line 6, there must be only one top-level public class defined in a source file. In addition, the file may include multiple top-level package-private classes.

Looking at line 8, we note that Java applications must have a main method. This method is the entry point into a Java program, and it must be defined. The modifiers must be declared public, static, and void. The arguments parameter provides a string array of command-line arguments.

TIP

Container-managed application components (e.g., Spring and Java EE) do not have a main method.

In lines 12 and 13, the statements provide calls to the System.out.print and System.out.println methods to print out the supplied text to the console window.

Command-Line Tools

A JDK provides several command-line tools that aid in software development. Commonly used tools include the compiler, launcher/interpreter, archiver, and documenter. Find a complete list of tools at Oracle.com.

Java Compiler

The Java compiler translates Java source files into Java bytecode. The compiler creates a bytecode file with the same name as the source file but with the .class extension. Here is a list of commonly used compiler options:

javac [-options] [source files]

Compiles Java source files.

javac HelloWorld.java

Compiles the program to produce HelloWorld.class.

javac –cp /dir/Classes/ HelloWorld.java

The –cp and –classpath options are equivalent and identify classpath directories to utilize at compile time.

javac –d /opt/hwapp/classes HelloWorld.java

The –d option places generated class files into a preexisting specified directory. If there is a package definition, the path will be included (e.g., /opt/hwapp/classes/com/oreilly/tutorial/).

javac –s /opt/hwapp/src HelloWorld.java

The –s option places generated source files into a preexisting specified directory. If there is a package definition, the path will be further expanded (e.g., /opt/hwapp/src/com/oreilly/tutorial/).

javac –source 1.4 HelloWorld.java

The –source option provides source compatibility with the given release, allowing unsupported keywords to be used as identifiers.

javac –X

The –X option prints a synopsis of nonstandard options. For example, –Xlint:unchecked enables recommended warnings, which prints out further details for unchecked or unsafe operations.

TIP

Even though –Xlint and other -X options are commonly found among Java compilers, the –X options are not standardized, so their availability across JDKs should not be assumed.

javac –version

The –version option prints the version of the javac utility.

javac –help

The –help option, or the absence of arguments, will cause the help information for the javac command to be printed.

Java Interpreter

The Java interpreter handles the program execution, including launching the application. Here is a list of commonly used interpreter options.

java [-options] class [arguments…]

Runs the interpreter.

java [-options] –jar jarfile [arguments…]

Executes a JAR file.

java HelloWorld

Starts the JRE, loads the class HelloWorld, and runs the main method of the class.

java com.oreilly.tutorial.HelloWorld

Starts the JRE, loads the HelloWorld class under the com/oreilly/tutorial/ directory, and runs the main method of the class.

java -cp /tmp/Classes HelloWorld

The –cp and –classpath options identify classpath directories to use at runtime.

java –Dsun.java2d.ddscale=true HelloWorld

The –D option sets a system property value. Here, hardware accelerator scaling is turned on.

java –ea HelloWorld

The –ea and –enableassertions options enable Java assertions. Assertions are diagnostic code that you insert in your application. For more information on assertions, see Assert Statement.

java -da HelloWorld

The –da and –disableassertions options disable Java assertions.

java –client HelloWorld

The –client option selects the client virtual machine to enhance interactive applications such as GUIs.

java –server HelloWorld

The –server option selects the server virtual machine to enhance overall system performance.

java –splash:images/world.gif HelloWorld

The –splash option accepts an argument to display a splash screen of an image prior to running the application.

java –version

The –version option prints the version of the Java interpreter, the JRE, and the virtual machine.

java [-d32 | -d64]

The [-d32] and the [-d64] options call for the use of the 32-bit or the 64-bit data model (respectively), if available.

java –help

The –help option, or the absence of arguments, will cause the help information for the java command to be printed.

javaw <classname>

On the Windows OS, javaw is equivalent to the java command but without a console window. The Linux equivalent is accomplished by running the java command as a background process with the ampersand: java <classname> &.

Java Program Packager

The Java Archive (JAR) utility is an archiving and compression tool, typically used to combine multiple files into a single file called a JAR file. JAR consists of a ZIP archive containing a manifest file (JAR content describer) and optional signature files (for security). Here is a list of commonly used JAR options along with examples:

jar [options] [jar-file] [manifest-files] [entry-point] [-C dir] files…

This is the usage for the JAR utility.

jar cf files.jar HelloWorld.java com/oreilly/tutorial/HelloWorld.class

The c option allows for the creation of a JAR file. The f option allows for the specification of the filename. In this example, HelloWorld.java and com/oreilly/tutorial/HelloWorld.class are included in the JAR file.

jar tfv files.jar

The t option is used to list the table of contents of the JAR file. The f option is used to specify the filename. The v option lists the contents in verbose format.

jar xf files.jar

The x option allows for the extraction of the contents of the JAR file. The f option allows for the specification of the filename.

TIP

Several other ZIP tools (e.g., 7-Zip, WinZip, and Win-RAR) can work with JAR files.

JAR File Execution

JAR files can be created so that they are executable by specifying the file within the JAR where the “main” class resides, so the Java interpreter knows which main() method to utilize. Here is a complete example of making a JAR file executable:

1. Create a HelloWorld.java file from the HelloWorld class at the beginning of this chapter.

2. Create the subfolders com/oreilly/tutorial/.

3. Run javac HelloWorld.

Use this command to compile the program and place the HelloWorld.class file into the com/oreilly/tutorial/ directory.

4. Create a file named Manifest.txt in the directory where the package is located. In the file, include the following line specifying where the main class is located:

Main-Class: com.oreilly.tutorial.HelloWorld

5. Run jar cmf Manifest.txt helloWorld.jar com/oreilly/tutorial.

Use this command to create a JAR file that adds the Manifest.txt contents to the manifest file, MANIFEST.MF. The manifest file is also used to define extensions and various package-related data:

Manifest-Version: 1.0

Created-By: 1.7.0 (Oracle Corporation)

Main-Class: com.oreilly.tutorial.HelloWorld

6. Run jar tf HelloWorld.jar.

Use this command to display the contents of the JAR file:

META-INF/

META-INF/MANIFEST.MF

com/

com/oreilly/

com/oreilly/tutorial

com/oreilly/tutorial/HelloWorld.class

7. Finally, run java –jar HelloWorld.jar.

Use this command to execute the JAR file.

Java Documenter

Javadoc is a command-line tool used to generate documentation on source files. The documentation is more detailed when the appropriate Javadoc comments are applied to the source code; see Comments. Here is a list of commonly used javadoc options and examples:

javadoc [options] [packagenames] [sourcefiles]

This is the usage to produce Java documentation.

javadoc HelloWorld.java

The javadoc command generates HTML documentation files: HelloWorld.html, index.html, allclasses-frame.html, constant-values.html, deprecated-list.html, overview-tree.html, package-summary.html, etc.

javadoc –verbose HelloWorld.java

The –verbose option provides more details while Javadoc is running.

javadoc –d /tmp/ HelloWorld.java

This –d option specifies the directory where the generated HTML files will be extracted to. Without this option, the files will be placed in the current working directory.

javadoc –sourcespath /Classes/ Test.java

The –sourcepath option specifies where to find user .java source files.

javadoc –exclude <pkglist> Test.java

The –exclude option specifies which packages not to generate HTML documentation files for.

javadoc –public Test.java

The –public option produces documentation for public classes and members.

javadoc –protected Test.java

The –protected option produces documentation for protected and public classes and members. This is the default setting.

javadoc –package Test.java

The –package option produces documentation for package, protected, and public classes and members.

javadoc –private Test.java

The –private option produces documentation for all classes and members.

javadoc –help

The –help option, or the absence of arguments, causes the help information for the javadoc command to be printed.

Classpath

The classpath is an argument set used by several command-line tools that tells the JVM where to look for user-defined classes and packages. Classpath conventions differ among operating systems.

On Microsoft Windows, directories within paths are delineated with backslashes, and the semicolon is used to separate the paths:

-classpath \home\XClasses\;dir\YClasses\;.

On POSIX-compliant operations systems (e.g., Solaris, Linux, and Mac OS X), directories within paths are delineated with forward slashes and the colon is used to separate the paths:

-classpath /home/XClasses/:dir/YClasses/:.

TIP

The period represents the current working directory.

The CLASSPATH environmental variable can also be set to tell the Java compiler where to look for class files and packages:

rem Windows

set CLASSPATH=classpath1;classpath2

# Linux, Solaris, Mac OS X

# (May vary due to shell specifics)

setenv CLASSPATH classpath1:classpath2