This chapter familiarizes you with basic elements of Java and how to write a simple Java program. A comprehensive understanding of the Java development environment is achieved through simple explanations of the application development process. A Java console program is provided that serves as a starting point and a reference point for this discussion.
In this chapter we will examine:
What Java is
The object-oriented development process
Types of Java applications
The creation of a simple program
The definition of classes and interfaces
Java Application Development
Java environment
Java documentation techniques
The use of annotations in Java
The core Java packages
Sun Microsystems developed the original specifications for the language in the mid 1990s. Patrick Naughton, Mike Sheridan, and James Gosling were the original inventors of Java and the language was called Oak at the beginning.
Java is a full-fledged object-oriented programming language. It is platform independent and is normally interpreted rather than compiled like C/C++. It is syntactically and structurally modeled after C/C++ and performs various compile-time and run-time checking operations. Java performs automatic memory management that helps to greatly reduce the problem of memory leaks found in other languages and libraries that dynamically allocate memory.
Java supports many features that, at its time of conception, were not found directly in other languages. These features include threading, networking, security, and Graphical User Interface (GUI) development. Other languages could be used to support these capabilities, but they were not integrated in the language to the extent that it was done with Java.
Java uses an independent bytecode that is architecture neutral. That is, it is designed to be machine independent. The byte codes are interpreted and executed by a Java Virtual Machine (JVM). All of its primitive data types are fully specified, as we will see in Chapter 3, Decision Constructs. The various releases of the Java Development Kit (JDK) and other significant moments are depicted in the following timeline diagram:
Let's digress for a moment and consider why we are using Java at all. One of the most significant aspects of Java is that it is an object-oriented (OO) language. OO technologies are a popular paradigm for developing applications. This approach models an application around a series of real world objects, such as an employee or a ship. In order to solve a problem, it is useful to think of the real world objects that make up the problem domain.
The OO approach is based on three distinct activities:
Object Oriented Analysis (OOA ): This is concerned with determining the functionality of the system, that is, what should the application do
Object Oriented Design (OOD): This is concerned with how the architecture supports the functionality of the application
Object Oriented Programming (OOP): This is concerned with the actual implementation of the application
The products of the analysis and design steps are often referred to as analysis and design artifacts. While there may be several different types produced, the one of most interest to the OOP step is called the class diagram
. The following diagram shows a partial class UML diagram depicting two classes: Customer
and CustomerDriver
. In the A simple Java application section, we will examine the code for these classes. The Unified Modeling Language (UML) is a widely used OO technique used to design and document an application. A class diagram is one of the end products of the technique and is used by programmers to create the application:
Each box represents a class and is divided into three sections:
The first section at the top of the box is the name of the class
The second section lists the variables that make up the class
The last section lists the class methods
The symbols preceding the variable and method names specify the visibility of these class members. The following are the class diagram symbols used:
-
: Private+
: Public#
: Protected (used with inheritance)
Normally, a class diagram consists of many classes and is interconnected with annotated lines showing the relationship between the classes.
The class diagram is intended to clearly show what objects make up the system and how they interact. Once a class diagram is complete it can be implemented using an OOP language such as Java.
Note
The object-oriented approach is typically used for medium-scale to large-scale projects, where many developers must communicate, and work together, to create an application. For smaller projects involving only a few programmers, such as the one dealt with in most programming classes, the object-oriented approach is not normally used.
While there is some disagreement in what actually makes a programming language an OOP programming language, there are generally three underlying principles that must be supported by an OOP language:
Data encapsulation
Inheritance
Polymorphism
Data encapsulation is concerned with hiding irrelevant information from the users of a class and exposing the relevant. The primary purpose of data encapsulation is to reduce the level of software development complexity. By hiding the details of what is needed to perform an operation, the use of that operation is simpler. How to achieve data encapsulation in Java is explained in the Access modifiers section, later in this chapter.
Data encapsulation is also used to protect the internal state of an object. By hiding the variables that represent the state of an object, modifications to the object are controlled through the methods. Any changes to the state are verified by the code in the methods. Also, by hiding variables, sharing of information between classes is eliminated. This reduces the amount of coupling possible in an application.
Inheritance describes the relationship between two classes such that one class re-uses the capabilities of another class. This enables the re-use of software resulting in a more productive developer. Inheritance is covered in detail in Chapter 7, Inheritance and Polymorphism.
The third principle is polymorphism and its primary concern is to make the application more maintainable and extendable polymorphism behavior is where the behavior of one or identical methods is dependent upon the object it is executing against. For example, a person
object and a square
object can both have a draw
method. What it draws depends on the object the method is executed against. Polymorphism is discussed in Chapter 7, Inheritance and Polymorphism.
These principles are summarized in the following table:
Principle |
What it is |
Why we use it |
How to do it |
---|---|---|---|
Technique that hides information from the users of that class |
To reduce the level of software development complexity |
Use access modifiers such as | |
Technique to allow a derived or child class to use parts of a base or parent class |
To promote the re-use of the software |
Use the | |
Technique which supports different behavior of methods that is dependent on the object the method is executing against |
To make an application more maintainable |
Inherent to the Java language |
The implements
keyword is used in support of polymorphic behavior as is explained in Chapter 7, Inheritance and Polymorphism.
There are several types of Java applications. These types have allowed Java to flourish in a number of different areas and contributed to Java becoming a very popular programming language. Java is used to develop the following:
Console and window applications
Server-based web applications supported by Servlets, JSPs, JSF, and other JEE standards
Applets that execute within a browser
Embedded applications
Componentized building blocks using JavaBeans
While a basic understanding of the types of Java applications is useful in putting Java into context, it also helps to be able to recognize the basic code for these applications. You may not completely understand all of the ins and outs of these application types, but it is useful to see simple code examples.
Reading the code goes a long way towards understanding a language and a specific program. Throughout the book we will use numerous examples to illustrate and explain various aspects of Java. The basic types of Java applications are shown below by presenting short code snippets that are central to that application type.
A simple console application consists of a single class with a main
method, as shown in the following code snippet:
public class Application { public static void main(String[] args) { // Body of method } }
We will examine this type of application in more depth.
Applets
are normally embedded within an HTML page and offer a means of achieving client-side execution of a code. It does not have a main
method but uses a series of callback methods used by the browser to manage the application. The following code provides an idea of the general appearance of an applet:
import java.applet.*; import java.awt.Graphics; public class SimpleApplet extends Applet { @Override public void init() { // Initialization code } @Override public void paint( Graphics g ) { // Display graphics } }
The @Override
annotation is used to ensure that the method that follows is actually overridden. This is discussed in more detail in the Annotations section of this chapter.
A servlet
is a server-side application which renders an HTML page sent to a client. A doGet
or doPut
method responds to client-side request. The out
variable in the following example represents the HTML page. The println
methods are used to write the HTML code, as shown in the following code snippet:
class Application extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); // then get the writer and write the response data PrintWriter out = res.getWriter(); out.println( "<HEAD><TITLE> Simple Servlet</TITLE></HEAD><BODY>"); out.println("<h1> Hello World! </h1>"); out.println( "<P>This is output is from a Simple Servlet."); out.println("</BODY>"); out.close(); } }
A JavaServer Page (JSP) is actually a disguised Servlet. It provides a more convenient way of developing web pages. The following example uses a JavaBean to display "Hello World" on the web page. The JavaBean is detailed in the following example:
<html> <head> <title>A Simple JSP Page</title> </head> <body> Hello World!<br/> <% // This is a scriptlet that can contain Java code %> <hr> <jsp:useBean id="namebean" class="packt.NameBean" scope="session" > <jsp:setProperty name="namebean" property="name" value=" Hello world"" /> </jsp:useBean> <h1> <jsp:getProperty name="namebean" property="name" /></h1> </body> </html>
JavaBeans are building blocks for shared application functionality. They are frequently designed to be used in multiple applications and follow a standard naming convention. The following is a simple JavaBean designed to hold a name (it was used in the previous JSP page):
package packt; public class NameBean { private String name= "Default Name""; public String getName() { return this.name; } public void setName(String name) { this.name = name; } }
Enterprise Java Beans (EJB) are components designed to be used in a client/server configuration from a web server. This is a fairly specialized topic that is not relevant to the associate level of certification.
There are several other types of Java technologies such as JSF and Facelets that are a part of JEE. These are improvements over the older Servlet and JSP technologies used to develop web pages.
In this book we will only use simple Java console applications. This type of application is more than sufficient to explain the essence of Java.
Let's start with a simple Java program and then use it to explore many of the basic facets of Java. First, a Java application consists of one or more files located somewhere within a filesystem. The name of the files and their locations are both important, as we will see shortly.
Note
You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.
Our simple program defines a Customer
class and then uses it in the CustomerDriver
class as follows:
package com.company.customer; import java.math.BigDecimal; import java.util.Locale; public class Customer { private String name; private int accountNumber; private Locale locale; private BigDecimal balance; public Customer() { this.name = "Default Customer"; this.accountNumber = 12345; this.locale = Locale.ITALY; this.balance = new BigDecimal("0"); } public String getName() { return name; } public void setName(String name) throws Exception { if(name == null) { throw new IllegalArgumentException( "Names must not be null"); } else { this.name = name; } } public int getAccountNumber() { return accountNumber; } public void setAccountNumber(int accountNumber) { this.accountNumber = accountNumber; } public BigDecimal getBalance() { return balance; } public void setBalance(float balance) { this.balance = new BigDecimal(balance); } public String toString() { java.text.NumberFormat format = java.text.NumberFormat.getCurrencyInstance(locale); StringBuilder value = new StringBuilder(); value.append(String.format("Name: %s%n", this.name)); value.append(String.format("Account Number: %d%n", this.accountNumber)); value.append(String.format("Balance: %s%n", format.format(this.balance))); return value.toString(); } } package com.company.customer; public class CustomerDriver { public static void main(String[] args) { // Define a reference and creates a new Customer object Customer customer; customer = new Customer(); customer.setBalance(12506.45f); System.out.println(customer.toString()); }
The details of how to compile and execute this application are provided in the Developing Java applications without an IDE section. When this application is executed you will get the following output:
Name: Default Customer Account number: 12345 Balance: € 12.506,45
Understanding the application in detail The following sections detail the significant aspects of the example program. These will be elaborated upon later in more detail in the chapters that follow. Notice, that there are two classes in this application. The CustomerDriver
class contains the main
method and is executed first. An instance of the Customer
class is created and used within the main method.
The package statement specifies the class' com.company.customer
package. Packages provide a means of grouping similar classes, interfaces, enumerations, and exceptions together. They are discussed in more depth in the Packages section in Chapter 9, The Java Application.
The import
statement
indicates which packages and classes are used by the class. This allows the compiler to determine whether the package's members are used correctly. Packages need to be imported for all classes, with the exception of the following classes:
Found in the
java.lang
packageLocated in the current package (
com.company.customer
, in this case)Explicitly marked such as
java.text.NumberFormat
as used in theCustomer
class'toString
method
The first word of the class definition was the keyword, public
, which is a part of the support Java provides for object-oriented software development. In this context, it specifies that the class is visible outside the package. While not required, it is frequently used for most classes and brings us to the second keyword, class
, which identifies a Java class.
Four private instance variables were declared next. The use of the private
keyword hides them from users of the class. The Locale
class supports applications that can work transparently internationally. BigDecimal
is the best way of representing currency in Java.
By making these instance variables private, the designer restricts access to the variables. They are then only accessible through public methods. The combination of private variables and public methods is an example of data encapsulation. If the instance variables are made public instead, other users can directly access the variables. This would improve the efficiency of the program, but may hinder future maintenance efforts. It would be more difficult to change these variables and enforce any sort of validation checks on the changes to the variables.
A series of getter and setter methods were present to return and set the values associated with the private instance variables. This exposes them in a controlled manner. The use of getter and setter methods is a standard approach to achieve encapsulation. For example, trying to assign a null value to a name would throw a IllegalArmumentException
exception. These types of methods are discussed in the Method declaration section.
The toString
method returns a string representing an instance of a customer. In this case the name, account number, and a localized version of the balance is returned. The use of the StringBuilder
class is discussed in Chapter 2, Java Data Types and Their Usage.
The CustomerDriver
class is referred to as the driver or controller class. Its purpose is to have a main
method that will create and use other classes.
In a Java application the main
method is the first method to be executed. If the application consists of multiple classes, normally only one class has a main
method. A Java application typically needs only one main
method.
In the main
method, a new customer is created, a balance is set and then the customer is displayed. A C++ style comment was added to statements to document the declaration and creation of a customer. This was the line beginning with the double forward slashes (//
). Comments are explained in detail in the Comments section.
Programming can be thought of as code manipulating data. In Java, code is organized around the following:
Packages
Classes
Methods
Packages are collections of classes with similar functionality. Classes are composed of methods that support the functionality of the class. This organization provides structure to applications. Classes will always be in a package and methods will always be in a class.
Note
If the package statement is not included in a class definition, the class becomes part of a default package which consists of all of the classes in the same directory that doesn't have a package statement.
A class is the fundamental building block of object-oriented programs. It generally represents a real-world object. A class definition in Java consists of member variable declarations and method declarations. It begins with the class
keyword. The body of the class is enclosed with brackets and contains all instance variables and methods:
class classname { // define class level variables // define methods }
Note
A pair of open and close curly braces constitutes a block statement. This is used in many other parts of Java.
A class is a pattern or template for creating multiple objects with similar features. It defines the variables and methods of the class. It declares the capabilities of the class. However, before these capabilities can be used, an object must be created. An object is an instantiation of a class. That is, an object is composed of the memory allocated for the member variables of the class. Each object has its own set of member variables.
Note
The following occurs when a new object is created:
The new keyword is used to create an instance of a class
Memory is physically allocated for the new instance of the class
Any static initializers are executed (as detailed in the Java initialization sequence section in Chapter 6, Classes, Constructors, and Methods)
A constructor is called to do initialization
A reference to the object is returned
The state of an object is typically hidden from the users of the object and is reflected in the value of its instance variables. The behavior of an object is determined by the methods it possesses. This is an example of data encapsulation.
Note
An object is the instantiation of a class. Each instance of a class has its own unique set of instance variables.
Objects in Java are always allocated on the heap. The heap is an area of memory that is used for dynamically allocated memory, such as objects. In Java, objects are allocated in a program and then released by the JVM. This release of memory is called garbage collection and performed automatically by the JVM. An application has little control over this process. The primary benefit of this technique is the minimization of memory leaks.
Note
A memory leak occurs when memory is dynamically allocated but is never released. This has been a common problem with languages such as C and C++, where it is the responsibility of the programmer to manage the heap.
A memory leak can still occur in Java if an object is allocated but the reference to the object is never released when the object is no longer needed.
Constructors are used to initialize an object. Whenever an object is created, a constructor executes. A default constructor is the one that has no arguments and is provided automatically for all classes. This constructor will initialize all instance variables to default values.
However, if the developer provides a constructor, the compiler's default constructor is no longer added. The developer will need to explicitly add a default constructor. It is a good practice to always have a default, no-argument constructor.
An interface is similar to an abstract class. It is declared using the interface
keyword and consists of only abstract methods and final variables. An abstract class normally has one or more abstract methods. An abstract method is the one that does not have an implementation. It is intended to support polymorphic behavior, as discussed in Chapter 7, Inheritance and Polymorphism. The following code defines an interface used to designate a class as capable of being drawn:
interface Drawable { final int unit = 1; public void draw(); }
All executable code executes either within an initializer list or a method. Here, we will examine the definition and use of methods. The initializer list is discussed in Chapter 6, Classes, Constructors, and Methods. Methods will always be contained within a class. The visibility of a method is controlled by its access modifiers as detailed in the Access modifiers section. Methods may be either static or instance. Here, we will consider instance methods. As we will see in Chapter 6, Classes, Constructors, and Methods, static methods typically access static variables that are shared between objects of a class.
Regardless of the type of method, there is only a single copy of a method. That is, while a class may have zero, one, or more methods, each instance of the class (an object) uses the same definition of the method.
An option modifier
A return type
The method name
A parameter list enclosed in parentheses
An optional throws clause
A block statement containing the method's statements
The following setName
method illustrates these parts of a method:
public void setName(String name) throws Exception { if(name == null) { throw new Exception("Names must not be null"); } else { this.name = name; } }
While the else clause in this example is technically not required, it is a good practice to always use else clauses as it represents a possible execution sequence. In this example, if the if statement's logical expression evaluates to true, then the exception will be thrown and the rest of the method is skipped. Exception handling is covered in detail in Chapter 8, Handling Exceptions in an Application.
Methods frequently manipulate instance variables to define the new state of an object. In a well designed class, the instance variables can typically only be changed by the class' methods. They are private to the class. Thus, data encapsulation is achieved.
Methods are normally visible and allow the user of the object to manipulate that object. There are two ways to classify methods:
In the Customer
class, setter and getter methods were provided for all of the instance variables, except for the locale variable. We could have easily included a get and set method for this variable but did not, to conserve space.
Note
A variable that has a get method but not an otherwise visible set method is referred to as a read-only member variable . The designer of the class decided to restrict direct access to the variable.
A variable that has a set method but not an otherwise visible get method is referred to as a write-only member variable . While you may encounter such a variable, they are rare.
The signature of a method consists of:
The name of the method
The number of arguments
The types of the arguments
The order of the arguments
The signature is an important concept to remember and is used in overloading/overriding methods and constructors as discussed in Chapter 7, Inheritance and Polymorphism. A constructor will also have a signature. Notice that the definition of a signature does not include the return type.
The examples used in the book will be console program applications. These programs typically read from the keyboard and display the output on the console. When a console application is executed by the operating system, the main
method is executed first. It may then execute other methods.
The main
method can be used to pass information from the command line. This information is passed to the arguments of the main
method. It consists of an array of strings representing the program's parameters. We will see this in action in Chapter 4, Using Arrays and Collections.
There is only one form of the main
method in Java, shown as follows:
public static void main(String[] args) { // Body of method }
The following table shows elements of the main method:
Elements |
Meaning |
---|---|
| |
|
The method can be invoked without creating an object of the class type. |
| |
|
The main
method returns void
, meaning that it is not possible to return a value back to the operating system as part of the normal method invocation sequence. However, it is sometimes useful to return a value to indicate whether the program terminated successfully or not. This is useful when the program is used in a batch type operation where multiple programs are being executed. If one program fails in this execution sequence, then the sequence may be altered. Information can be returned from an application using the System.exit
method. The following use of the methods will terminate the application and return a zero to the operating system:
System.exit(0);
Variables and methods can be declared as one of four types, shown in the following table:
Access type |
Keyword |
Meaning |
---|---|---|
|
Access is provided to users outside the class. | |
|
Restricts access to members of the class. | |
|
Access is provided to classes that inherit the class or are members of the same package. | |
none |
Access is provided to members of the same package. |
Most of the time, a member variable is declared as private and a method is declared as public. However, the existence of the other access types implies other potential ways of controlling the visibility of a member. These usages will be examined in Chapter 7, Inheritance and Polymorphism.
In the Customer
class, all of the class variables were declared as private and all of the methods were made public. In the CustomerDriver
class, we saw the use of the setBalance
and toString
methods:
customer.setBalance(12506.45f); System.out.println(customer.toString());
As these methods were declared as public, they can be used with the Customer
object. It is not possible to directly access the balance instance variable. The following statement attempts this:
customer.balance = new BigDecimal(12506.45f);
The compiler will issue a compile-time error similar to the following:
balance has private access in com.company.customer.Customer
The documentation of a program is an important part of the software development process. It explains the code to other developers and provides reminders to the developers of what and why they did what they did.
Documentation is achieved through several techniques. Here, we will address three common techniques:
Comment: This is the documentation embedded in the application
Naming conventions: Following the standard Java naming conventions makes an application more readable
Javadoc: This is a tool used to generate documentation about an application in the form of HTML files
Comments are used to document a program. They are not executable and are ignored by a compiler. Good comments can go a long way to make a program more readable and maintainable. Comments can be grouped into three types—C style, C++ style, and Java style, as summarized in the following table:
Type of Comment |
Description | |
---|---|---|
Example | ||
C style |
The C style comment uses a two character sequence at the beginning and the end of a comment. This type of comment can extend across multiple lines. The beginning character sequence is a | |
/* A multi-line comment … */ /* A single line comment */
| ||
C++ style |
The C++ style comment begins with two forward slashes and the comment continues until the end of the line. Essentially everything from the | |
// The entire line is a comment int total; // Comment used to clarify variable area = height*width; // This computes the area of a rectangle
| ||
Java Style |
The Java style is identical in syntax to the C style comment, except that it starts with | |
/** * This method computes the area of a rectangle * * @param height The height of the rectangle * @param width The width of the rectangle * @return The method returns the area of a rectangle * */ public int computeArea(int height, int width) { return height * width; }
|
Java uses a series of naming conventions to make the programs more readable. It is recommended that you always follow this naming convention. By doing so:
You make your code more readable
It supports the use of JavaBeans
Note
More detail on naming conventions can be found at http://www.oracle.com/technetwork/java/codeconvtoc-136057.html.
The Java naming conventions' rules and examples are shown in the following table:
Element |
Convention |
Example |
---|---|---|
Package |
All letters in lowercase. |
|
Class |
First letter of each word is capitalized. |
|
Interface |
First letter of each word is capitalized. |
|
Variable |
First word is not capitalized but the subsequent words are capitalized |
|
Method |
First word is not capitalized but subsequent words are capitalized. Methods should be verbs. |
|
Constant |
Every letter is uppercase. |
|
The Javadoc tool produces a series of HTML files based on the source code and Javadoc tags embedded in the source code. This tool is also distributed with the JDK. While the following example is not an attempt to provide a complete treatment of Javadocs, it should give you a good idea of what Javadocs can do for you:
public class SuperMath { /** * Compute PI - Returns a value for PI. * Able to compute pi to an infinite number of decimal * places in a single machine cycle. * @return A double number representing PI */ public static double computePI() { // } }
The javadoc
command, when used with this class, results in the generation of several HTML files. A part of the index.html
file is shown in the following screenshot:
Note
More information on the use and creation of Javadoc files can be found at http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html.
Java source code is compiled to intermediate bytecode. The bytecode is then interpreted at runtime on any platform that has a Java Virtual Machine (JVM). However, this statement is somewhat misleading as Java technology will often compile bytecode directly to machine code. There have been numerous Just-In-Time compiler improvements that speed up the execution of Java applications that often will run nearly as fast as, or sometimes even faster than, natively-compiled C or C++ applications.
Java source code is found in files that end with a .java
extension. The Java compiler will compile the source code to a bytecode representation and store these bytecodes in a file with a .class
extension.
There are several Integrated Development Environments (IDE) used to support the development of Java applications. A Java application can also be developed from the command line using basic tools from the Java Development Kit (JDK).
A production Java application is normally developed on one platform and then deployed to another. The target platform needs to have a Java Runtime Environment (JRE) installed on it in order for the Java application to execute. There are several tools that assist in this deployment process. Typically, a Java application is compressed in a Java Archive (JAR) file and then deployed. A JAR file is simply a ZIP file with a manifest document embedded within the JAR file. The manifest document often details the content and the type of JAR file being created.
The general steps used to develop a Java application include:
Create the application using an editor
Compile it using the Java compiler (
javac
)Execute it using the Java interpreter (
java
)Optionally debug the application as required using a Java debugger
This process is summarized in the following diagram:
Java source code files are compiled to bytecode files. These bytecode files have a .class extension. When a Java package is distributed, the source code files are not normally stored in the same location as the .class
files.
The Java Software Development Kit (SDK) can be downloaded and used to create and execute many types of Java applications. The Java Enterprise Edition (JEE) is a different SDK and is used to develop enterprise applications typified by web-based applications. The SDK also known as the Java 2 Enterprise Edition (J2EE) and you may see it referenced as J2EE. Here, we will only deal with the Java SDK.
While the actual structure of the SDK distribution will vary by release, the typical SDK consists of a series of directories, listed as follows:
The SDK may include the actual source code for the core classes. This is usually found in the src.zip
file located under the JAVA_HOME
root directory.
Each IDE has a preferred way of organizing the files that make up an application. These organization schemes are not always hard and fast but those presented here are the common ways of arranging the files.
For example, a simple application in the Eclipse IDE consists of two project files and three sub-directories. These files and directories are listed as follows:
.classpath
: This is an XML file containing the classpath-related information.settings
: This is a directory containing theorg.eclipse.jdt.core.prefs
file which specifies compiler preferencesbin
: This is used to contain the package file structure and the application's class filessrc
: This is used to contain the package file structure and the application's source files
This organization scheme is used by the development tools. The tools often include editors, compilers, linkers, debuggers, and others. These languages frequently use a Make tool to determine which files need to be compiled or otherwise manipulated.
In this section we will demonstrate how to compile and execute a Java application on a Windows platform using Java 7. The approach is very similar to that used for other operating systems.
Before we can compile and execute the sample program we need to:
Install the JDK
Create the appropriate file structure for the application
Create the files to hold our classes
The latest version of the JDK can be found at http://www.oracle.com/technetwork/java/javase/downloads/index.html. Download and install the version that meets your needs. Note the location of the installation, as we will use this information shortly.
As explained earlier, the Java classes must be located in a specific file structure as mirrored in its package name. Create a file structure somewhere in your filesystem that has a top-level directory called com
under which is a directory called company
and then under the company
directory, a directory called customer
.
In the customer
directory create two files called Customer.java
and CustomerDriver.java
. Use the corresponding classes as found earlier in the A simple Java application section.
The JDK tools are found in the JDK directory. When the JDK is installed, the environmental variables are normally set up to allow the successful execution of the JDK tools. However, it is necessary to specify the location of these tools. This is accomplished using the set
command. In the following command, we set the path environmental variable to reference C:\Program Files\Java\jdk1.7.0_02\bin directory
, which was the most recent release at the time this chapter was written:
set path= C:\Program Files\Java\jdk1.7.0_02\bin;%path%
This command prefixes the path to the bin
directory in front of any previously assigned paths. The path
environmental variable is used by the operating system to look for the command that is executed at the command prompt. Without this information, the operating system is not aware of the location of the JDK commands.
To compile
the program using the JDK, navigate to the directory above the com
directory. As the classes used as part of this application are part of the com.company.customer
package we need to:
Specify the path in the
javac
commandExecute the command from the directory above the
com
directory
As there are two files that make up this application we need to compile both of them. This can be done using two separate commands as follows:
javac com.company.customer.Customer.java javac com.company.customer.CustomerDriver.java
Or, it can be done using a single command and the asterisk wild card character as follows:
javac com.company.customer.*.java
The output of the compiler is a bytecode file with the name CustomerDriver.class
. To execute the program, invoke the Java interpreter with your class file, as shown in the following command. The class extension is not included and its inclusion as part of the filename will result in an error:
java com.company.customer.CustomerDriver
The output of your program should be as follows:
Name: Default Customer Account number: 12345 Balance: € 12.506,45
The Java environment is the operating system and file structure used to develop and execute Java applications. Earlier, we examined the structure of the JDK which are part of the Java environment. Associated with this environment are a series of environmental variables that are used from time-to-time to facilitate various operations. Here, we will examine a few of them in more detail:
CLASSPATH
PATH
JAVA_VERSION
JAVA_HOME
OS_NAME
OS_VERSION
OS_ARCH
These variables are summarized in the following table:
Name |
Purpose |
Example |
---|---|---|
|
Specifies the root directory for classes. |
|
The location of the commands. | ||
The version of Java to use. |
| |
The location of the Java directory. |
| |
The name of the operating system. |
Windows 7 | |
The version of the operating system |
6.1 | |
The operating system architecture |
AMD64 |
The CLASSPATH
environmental variable is used to identify the root directory of the packages. It is set as follows:
c:>set CLASSPATH=d:\development\increment1;%CLASSPATH%
The CLASSPATH
variable only needs to be set for non-standard packages. The Java compiler will always implicitly append the system's class directories to CLASSPATH
. The default CLASSPATH
is the current directory and the system's class directories.
There are many other environmental variables associated with an application. The following code sequence can be used to display a list of these variables:
java.util.Properties properties = System.getProperties(); properties.list(System.out);
A partial display of the output of this code sequence is as follows:
-- listing properties -- java.runtime.name=Java(TM) SE Runtime Environment sun.boot.library.path=C:\Program Files\Java\jre7\bin java.vm.version=22.0-b10 java.vm.vendor=Oracle Corporation java.vendor.url=http://java.oracle.com/ path.separator=; java.vm.name=Java HotSpot(TM) 64-Bit Server VM …
Annotations provide information about a program. This information does not reside in the program and does not affect its execution. Annotations are used to support tools such as the compiler and during the execution of the program. For example, the @Override
annotation informs the compiler that a method is overriding a base class method. If the method does not actually override the base class method because it is misspelled, the compiler will generate an error.
Annotations are applied to elements of the application such as a class, method, or field. It begins with the at sign, @
, is followed by the name of the annotation, and optionally a list of values enclosed in a set of parentheses.
Common compiler annotations are detailed in the following table:
Annotation |
Usage |
---|---|
Used by the compiler to indicate that the element should not be used | |
|
The method overrides the base class method |
Used to suppress specific compiler warnings |
Annotations can be added to an application and used by the third-party tools for specific purposes. It is also possible to write your own annotations when needed.
Java includes a number of libraries of classes that support the development of applications. These include the following, among others:
java.lang
java.io
java.net
java.util
java.awt
These libraries are organized in packages. Each package holds a set of classes. The structure of a package is reflected in its underlying file system. The CLASSPATH
environmental variable holds the location of packages.
There are a core set of packages that are part of the JDK. These packages provide a crucial element in the success of Java by providing easy access to a standard set of capabilities that were otherwise not readily available with other languages.
The following table shows a list of some of the more commonly used packages:
In this chapter we examined the essential aspects of Java and a simple Java console application. From a certification standpoint we looked at the structure of a class and a Java application that uses the main
method.
We also introduced a number of additional topics that will be covered in more detail in later chapters. This includes the creation of objects and their manipulation, the use of strings and the StringBuilder
class, instance and static members of a class, and the use of signatures in the overloading and overriding of a method.
With this foundation we are ready to move on to Chapter 2, Java Data Types and Their Usage, where we will examine the nature of variables and how they can be used.
In this chapter we introduced a number of certification topics that will be discussed in more detail in subsequent chapters. Here we covered the following topics in depth:
Define the structure of a Java class (in the Exploring the structure of a class section)
Create an executable Java application with a main method (in the Exploring the structure of a Java console program section)
1. What will be printed out if the following code is run with the
java SomeClass hello world
command?public class SomeClass{ public static void main(String argv[]) { System.out.println(argv[1]); } }
a.
world
b.
hello
c.
hello
world
d.
ArrayIndexOutOfBoundsException
is thrown2. Consider the following code sequence:
public class SomeClass{ public int i; public static void main(String argv[]){ SomeClass sc = new SomeClass(); // Comment line } }
Which of the following statements will compile without syntax or runtime errors if they replace the comment line?
a.
sc.i = 5;
b.
int j = sc.i;
c.
sc.i = 5.0;
d.
System.out.println(sc.i);