Skip to main content
main-content
Top

About this book

This book presents a guide to the core features of Java – and some more recent innovations – enabling the reader to build skills and confidence though tried-and-trusted stages, supported by exercises that reinforce key learning points. All of the most useful and commonly applied Java syntax and libraries are introduced, along with many example programs that can provide the basis for more substantial applications. Use of the Eclipse IDE and the JUnit testing framework is integral to the book, ensuring maximum productivity and code quality, although to ensure that skills are not confined to one environment the fundamentals of the Java compiler and run time are also explained.
Additionally, coverage of the Ant tool will equip the reader with the skills to automatically build, test and deploy applications independent of an IDE.
Features: presents information on Java 7; contains numerous code examples and exercises; provides source code, self-test questions and PowerPoint slides at an associated website.

Table of Contents

1. The Java Story

Abstract
Java is now well established as one of the world’s major programming languages, used in everything from desktop applications to web-hosted applications and enterprise systems, and embedded in devices such as mobile phones and Blu-ray players. Its virtual machine (a core feature of the Java runtime platform, which we will explore later) also supports a family of related languages including Scala, Groovy, and specialized versions of Ruby and Python. However, its beginnings were relatively humble and obscure, until it came to wider attention via the web in 1995. Within a year it had become “the next big thing” in software. Interest in the language was quite remarkable, considering that it only existed in beta test versions. In many ways it was a question of being the right product at the right time, its popularity riding on the explosion of interest in the Internet and World Wide Web in the mid-1990s.
David Parsons

2. Compiling and Running Java Programs

Abstract
In this chapter, we meet our first Java applications. These short programs consist of classes that contain some simple code that displays output on the screen. The main purpose of this chapter, however, is to gain an understanding of the Java compiler and runtime environment and learn how to use packages and the classpath. In the early examples, we will be exploring how to use Java from the command line to help gain a deeper understanding of what is going on. At the end of the chapter, we introduce the Eclipse Java Integrated Development environment (IDE), where many of the low-level processes are taken care of for you.
David Parsons

3. Data Types, Arithmetic, and Arrays

Abstract
In this chapter, we introduce Java’s primitive data types, arithmetic operators, String concatenation, and arrays. With these basic components, we can begin to build some useful programs. Along the way we look at some important concepts relating to how Java handles combinations of different data types, including promotion and casting.
David Parsons

4. Control Structures

Abstract
In this chapter, we look at the main control structures in Java that enable selection and iteration. For selection, we cover “if-else,” “switch,” “break,” and “continue” statements, and the ternary operator. For iterating over code, we explore the “while,” “do-while,” and “for” loops. We see how “for” loops can be used to iterate through arrays, including the array of Strings that is passed to the “main” method.
David Parsons

5. Creating Objects

Abstract
We have already seen that Java has both primitive types and reference types. We spent some time looking at primitive types in Chap. 3, but also introduced Strings and arrays, which are both reference types. Reference types include all kinds of classes, including user-defined types (e.g., BankAccount, InsurancePolicy, Customer), collection classes like Lists, simple data classes like Dates, and many more. There are a number of characteristics of reference types, but one general feature is that they are more complex data types than primitives, which just represent a single value. They are also represented by a reference that can refer to something in a specific area of memory.
David Parsons

6. Creating Domain Classes

Abstract
In the previous chapter, we created objects of some of the commonly used classes in the Java libraries, including Strings, Dates, and Points. However, in order to build useful software, we need to go beyond these generic library classes and reflect the concerns of our own application domains. In this chapter, we will begin to explore how we create new domain classes that can represent the objects of interest to us in our own applications.
David Parsons

7. Objects Working Together: Association, Aggregation, and Composition

Abstract
Many objects can be seen as being made up of smaller objects. For example, a clock is made up of a number of components that together combine to make the whole object. The combination of objects may exist in many layers, with a larger component (such as the mechanism) being itself made up of a collection of smaller components. Figure 7.1 shows a clock as a combination of component parts.
David Parsons

8. Inheritance, Polymorphism, and Interfaces

Abstract
From the classes and objects we have worked with so far, we recognize that identical objects belong to the same class, but what about objects that are similar rather than identical? How do we know, for example, that a particular object is a clock rather than any other type of object? We instinctively classify objects in the world to be of a particular type by recognizing what is common between different but similar objects. A clock is anything that tells the time in some way, regardless of the technology or appearance of a particular clock. The class “clock” encompasses all we understand about the general concept of “clockness.” A specific type of clock belongs to a specific class, but also to higher-level abstractions.
David Parsons

9. Exception Handling

Abstract
Exceptions are an important aspect of Java programming because they enable us to deal efficiently, and in an object-oriented manner, with unusual program flow, whether it is caused by technical issues or business processes. Prior to languages with built-in exception handling, such issues had to be dealt with by manually passing error codes around a program, without any encapsulation or standard ways of handling them.
David Parsons

10. Unit Testing with JUnit

Abstract
Testing has always been an important part of software development, but in recent years it has become more of a programmer activity, particularly with the growth in popularity of agile methods. Programmers are expected to be able to write and run unit tests against their code. A unit test is designed to test a single unit of code, for example, a single class, or part of a class.
David Parsons

11. Exploring the Java Libraries

Abstract
In this chapter, we will take a brief look at some of the commonly used classes in the Java libraries. The examples covered here are intended to be just a small sample of the possible set of classes that you might want to use. The main purpose of the chapter is to encourage you to reuse existing classes as much as possible in your programming, not to “reinvent the wheel.” One of the key things that object-oriented programming offers is the ability to reuse existing classes. Reuse has two major advantages. First, you save your own time by not having to implement the code. Second, code in standard libraries has already been extensively tested so there is no need to test it yourself. If you find yourself needing to perform a particular process or create a particular type of object, then you may find that a suitable implementation already exists in Java, particularly if the process or class could be considered to be a general purpose one rather than being domain specific. The most important thing is to become used to using the Javadoc as a frequent resource, checking to see what classes are in the library that you might be able to reuse before writing any new code.
David Parsons

12. The Collections Framework and Generics

Abstract
In this chapter, we will look at some classes from the Java Collections Framework that can be used to contain collections of other objects. This framework makes extensive use of both inheritance and interfaces to provide both reuse and consistency across many different types of collection. The components of the framework include familiar data structures such as arrays, lists, maps, and queues, as well as related algorithmic operations such as searching and sorting. The collections framework starts from the idea that every type of container is either a Collection or a Map. Both Collection and Map are interfaces that provide a common set of method signatures that all implementing classes should support. A Collection is something that contains elements, whereas a Map defines a mapping between keys and objects.
David Parsons

13. Input and Output Streams

Abstract
A stream is an ordered sequence of bytes flowing from a source to a destination. The implementation of Streams in Java aims to encapsulate any kind of serial input or output into a library of classes that provide a consistent set of abstractions (interfaces and abstract classes), regardless of the source or the sink (destination) of the data. The lower-level details specific to those types of source or destination are handled by the stream, and do not have to be handled by the programmer. For example, the differences between writing to a file and writing to the screen console are handled by the implementations of the relevant classes. From a programmer’s perspective, all we have to do is create an object of the appropriate type of stream class and use its methods. A program may write and read data to and from files, the console, the keyboard, networks, or other programs, all using similar methods, implemented by stream library classes that encapsulate the low-level differences between the various types of data transfer, providing higher-level abstractions for the programmer to use (Fig. 13.1).
David Parsons

14. Automatic Building and Testing with Ant

Abstract
Ant (“Another Neat Tool”) is a Java-based build tool which uses a combination of Java and XML to create platform-independent build and deploy scripts. Being written in Java, it has the advantage over some other build tools of working on any platform. It is open source and is available free from the Apache Software Foundation (http://ant.apache.org/). It uses an XML build file (called “build.xml” by default) containing targets and tasks. Ant is used in many Java projects and can be invoked directly from many other tools, including Eclipse. The Apache Ant project has spawned subprojects such as Ivy (a dependency manager). There are other similar tools around, such as Maven, but Ant is ideal for relatively simple builds.
David Parsons

15. Java and the Database (JDBC)

Abstract
The data in Java programs does not last beyond a single run of a program. Most applications require some more persistent storage of state than this, and in most cases we will use a database. While streaming data to and from a sequential file can be useful in some contexts, it does not allow the querying, performance, availability, and accessibility of database storage. Therefore, we need to know how to get data in and out of a database so we can use it in our applications. Although there are several different types of database available, including hierarchical, object-oriented, and XML, most current commercial databases are relational. The focus of this chapter is on how to bridge between the table schemas of a relational database and Java code using JDBC (Java Database Connectivity).
David Parsons

16. Multithreading

Abstract
One of the increasingly important features of Java, as multiprocessor computers have become commonplace, is that it allows us to write programs with multiple threads. Many programming languages run with a single thread of control, meaning that the program can do only one thing at a time. A multithreaded language allows programs to do more than one thing at the same time, to perform multiple tasks concurrently. Even on single processor, programs can appear to perform different tasks simultaneously by swapping between them at high speed. As a traditional mainframe computer can have many terminals connected to it at the same time, a single Java program can have many threads running at once. All Java programs have a main user thread, but other child threads can be spawned from it. These can be either user threads, like the thread that runs a “main” method, or demon threads running in the underlying virtual machine. There must be at least one user thread running for the program to continue. When you create your own threads, they are usually user threads, but can also be set to be demon threads. You might do this to ensure that these threads do not keep running after other user threads have stopped.
David Parsons

17. Building GUIs with the JFC Swing Library

Abstract
Graphical User Interface (GUI) libraries have a number of common characteristics. They usually provide interaction through a WIMP (Windows Icons Menus and Pointers) interface, with WYSIWYG (what you see is what you get) presentation. They enable a common look and feel across different applications, making it easy for users to switch between them and reducing the learning time for a new application that uses the same GUI library. Window appearance, including control components and menu placement, is consistent across multiple programs.
David Parsons

18. Event-Driven Programming

Abstract
In the previous chapter, we looked at how components could be created, configured, and arranged inside a container such as a JFrame. However, none of the components in the examples were able to process any events from the user. In this chapter, we will see how to write code than can respond to events such as buttons being pressed, text fields being changed, and the movements of the mouse.
David Parsons

19. Dialogs and Menus, Models and Views

Abstract
In a typical application, you want to give some information to, or get some information from, the user in different contexts. Dialogs provide pop-up windows that can provide focused modes of interaction for particular features of an application. Dialogs can be either modal or modeless; modal dialogs prevent the user from doing anything in the dialog’s parent application until the dialog has been dismissed. With a modeless dialog, the user can work in other windows of the application without dismissing the dialog.
David Parsons

20. Java Web Start and Applets

Abstract
In its early days, Java came to prominence because of Java applets, running in web browsers. Applets have had something of a checkered history since then, and most Java web technologies belong in the enterprise edition rather than the standard edition of Java. However, applets are still widely used, and can be a useful component of rich Internet applications. Also associated with the web, but less directly, is Java Web Start, which allows desktop applications to be deployed over the web. In this chapter, we will begin by looking at Java Web Start and then look at applets, which can now use the same deployment mechanism as Java Web Start, making it very easy to switch between the two modes of deployment. Since both Java Web Start and applets require us to create web pages with appropriate links to Java applications or applets, we will begin with brief overviews of web browsers, URLs, and HTML.
David Parsons
Additional information