Cover Page

INTRODUCTION

Congratulations! By picking up this book you have made the first step in your voyage toward learning Java. Java is a programming language with a long history, starting with its inception in 1991, when it was still named “Oak,” through the first public release (Java 1.0) in 1995 and the newly released Java 8. Its “write once, run anywhere” approach, together with robust language features and numerous libraries led to a spectacular adoption rate. Java is one of the most popular languages in use today, and has been especially successful in enterprise and business environments.

Note, however, that Java is not without its criticism (no programming language is). You might have picked upon the often-repeated criticism that Java is verbose, unsecure, suffering from a slow release cycle, and that it is fading in popularity compared to the interest in new, more exciting languages (Ruby, Erlang, and Haskell, to name a few) by the computer science and programmer communities. The reality, however, tells a different story. Java remains widely taught in schools and universities and is regarded as the language of choice in many organizations. The introduction of Java 7 in 2011 made many tasks simpler, and the availability of many seasoned and stable libraries, tools, and feature-complete IDEs is unmatched by the ecosystem found around other languages. In 2014, Java 8 introduced lambda expressions to streamline code and a reengineered date and time interface that simplifies and improves the internationalization of applications. Java’s strong architectural foundations make the language ideally suited for both newcomers and experienced programmers who want to expand their knowledge of Object-Oriented Programming.

Before reaching the end of this book, you will agree that being proficient in Java is a strong skill to possess indeed. We aim to get you started and up to speed as quickly as possible, without making sacrifices in terms of depth and breadth of topics. The goal is not to guide you in simply adding yet another (or first) language to your repertoire, but also to familiarize you with Java’s underlying approach toward robust and structured Object-Oriented Programming. As you will see, Java’s “verbosity” makes it ideally suited to teach programming best practices in an explicit manner. Providing step-by-step explanations together with many examples—inspired by real-life environments rather than toy exercises—will help you quickly appreciate Java’s design and usefulness, and learn that programming in Java can even be great fun!

WHO THIS BOOK IS FOR

Java is a great language to learn for both new and experienced programmers. As such, this book is geared towards a broad audience, including practitioners, analysts, programmers, and students wanting to apply Java in a pragmatic context. It doesn’t matter whether you are new to programming and have chosen Java as a place to start or whether you come in from another programming language; Java is a great choice. Many books exist on the topic of Java (just look at the shelf where you found this book!), but we feel that existing offerings reuse the same approach to demonstrate concepts. Therefore, you will not find the archetypical (and honestly, completely useless) “Hello World” example in this book. Instead, we delve into concrete, thought-out examples that illustrate how Java can be useful and used in real life. Whether you are an analyst struggling with spreadsheet formulas to perform a somewhat advanced calculation (there has to be a smarter way, right?), a student wondering how your future employer is using Java, or a hobbyist programmer trying to keep track of stock quotes or a book database, this book aims to familiarize you with all the necessary concepts.

TOPICS COVERED IN THIS BOOK

The topics discussed in this book can, broadly speaking, be outlined in the following three categories. First is a general introduction to programming and Java. The first chapters briefly discuss programming in general, before moving on to a high-level description of Java’s history and language features. We also make sure to set up everything you need to get started with Java.

The second part deals with Object-Oriented Programming in Java. The goal is to help readers acquire a strong knowledge of how Object-Oriented Programming works and how Java programs are structured.

The third part is more focused and practical, and shows how you can leverage Java to talk to data sources (such as files, databases, and even web services) and how you can create a graphical user interface around your program logic.

Note that we have not structured the book around the aforementioned three parts. Instead of splitting the book into “theoretical” and “practical” parts, we chose to introduce new concepts step-by-step as they are needed so that you can quickly move on to examples and exercises. The best way to learn is by doing, and this saying particularly holds true when learning to program.

In Chapter 1, we provide a brief general introduction to programming geared toward newcomers and novice programmers. In Chapter 2, we start introducing Java by providing an overview of the language’s history, the different technological components that make up the language, the general language structure, and data types. At that point, you will know enough to get started, so that in Chapter 3, we will guide you toward setting up your development environment and trying out some basic examples and exercises. In Chapter 4, we introduce Object-Oriented Programming basics; flow-control statements are covered in Chapter 5. At that point, you will be able to create simple but functional programs. Chapter 6 explains how to catch errors and debug your programs, which will come in handy as you start using resources and coding more advanced programs. At this point, you will have all the necessary components to start looking at some more advanced Object-Oriented Programming concepts in Chapter 7. After this, you’ll be ready to tackle more complex interactions with files, external sources, and users. In Chapter 8 you will look at dealing with file-based input and output, including how to load files, perform basic operations, and save the results back to disk. Chapters 9 and 10 build on this by explaining how to interact with databases and web sources. At this point, you will be itching to move away from command-line based applications, and Chapter 11 explains in-depth how to build graphical user interfaces. Chapter 12 concludes the theory by providing an overview of some common architectural patterns (best practices, if you will) used by seasoned Java developers.

By the end of this book, you will have gained a strong knowledge of Java’s internals, you will know what is meant by Object-Oriented Programming, know how to debug and deal with errors in your programs, know how to handle file-based input and output, talk to databases, talk to web services, make a full-fledged graphical application, and be familiar with some common and well-known programming “patterns,” which are best practices to structure and organize a program’s architectural setup.

TOPICS NOT COVERED IN THIS BOOK

This book is not a reference manual. The goal is to get readers acquainted with the basics of Java and Object-Oriented Programming to use within practical applications, not to provide a full overview of Java’s API. As such, given the scope of this book, there are some concepts that are not discussed in detail. However, we have taken care to avoid elements you can live without at this point in your Java career.

Working with generics in Java, for example, is not discussed explicitly, but instead explained briefly where needed (when we talk about collections in Java, such as lists or sets, for example). Working with generic classes can be daunting for novice Java programmers, and the Object-Oriented Programming concepts discussed suffice to cover the multitude of use cases. That said, familiarizing yourself with generic types after going through this book should not prove difficult.

Other topics that are not discussed in-depth include networking in Java (socket programming), multi-threaded and concurrent programming, reflection, and the lambda expressions introduced with Java 8. Networking aspects, however, are dealt with from a “higher-level” view. We discuss how to interact with web services, which provides a great starting point for practitioners to load data coming from the web. Concurrent, multi-threaded programming is a beneficial practice when performance and speed becomes an issue in applications, but for most use cases in a practical context, Java performs just fine without having to deal with multi-threading. Additionally, programming in a concurrent fashion introduces some particular challenges and “gotchas” that are unfit for beginning Java programmers to deal with. Reflection is a part of the Java API that allows programmers to examine and “reflect” on Java programs while they are running and perform changes to programs while they are being executed. While very helpful in some cases, it also is out of scope for a beginner’s book on Java. Finally, the recently released Java 8 introduces some new concepts, most notably lambda expressions. Java 7 also provides functionality to work with so-called “anonymous classes,” which are ad hoc implementations of a base class without a specific name or definition. Other than the fact that these classes can appear somewhat verbose, they are perfectly fine to use instead of lambda expressions (which provide the same functionality in a more concise manner) and are still widely used. We do, however, provide short notes on developments within Java 8 whenever appropriate.

Finally, Java is composed of a certain number of “technologies” (also called platform components). The “standard” Java is denoted as “Standard Edition” (SE), and is the one we tackle here. An Enterprise Edition (EE) also exists, as well as a number of extensions to develop embedded and mobile applications (Embedded Java and Java ME), applications for smart TVs (Java TV), and graphic-intensive applications (Java FX and Java 2D). We do not discuss these extensions in this book, as they have no place in a beginner’s book on Java. Readers wanting to apply Java in these specific areas should, however, be ready to move on to these more focused topics after reading this book.

CONVENTIONS

This book applies a number of styles and layout conventions to differentiate between the different types of information.

In addition to providing extensive examples in the form of Try It Outs, you will also encounter frequent tips, hints, advice, and background information, which are formatted like this:

Discussions that extend beyond a short tip or note will look a little bit different.

Finally, program code within this book is formatted in two ways. The first way is as code type: (/* Like this comment */). Variables (like iAmAVariable) appear in italic code type.

Larger code blocks look like the following:

public class NoHelloWorld {
    public static void main(String[] args) {
        System.out.println("This is not an Hello World program...");
    }
}

All these styles are designed to make sure it’s easy for you to know what you’re looking at while you read.

SOURCE CODE

As you work through the examples in this book, you may choose either to type in all the code manually or to use the source-code files that accompany the book. All of the source code used in this book is available for download at www.wrox.com. Once at the site, simply locate the book’s title (either by using the Search box or by using one of the title lists) and click the Download Code link on the book’s detail page to obtain all the source code for the book.

Once you download the code, just decompress it with your favorite compression tool. Alternately, you can go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.

ERRATA

We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty piece of code, we would be very grateful for your feedback. By sending in errata, you may save another reader hours of frustration, and at the same time you will be helping us provide even higher-quality information.

To find the errata page for this book, go to www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the book details page, click the Book Errata link. On this page you can view all errata that have been submitted for this book and posted by Wrox editors. A complete book list, including links to each book’s errata, is also available at www.wrox.com/misc-pages/booklist.shtml.

If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/techsupport.shtml and complete the form there to send us the error you have found. We’ll check the information and, if appropriate, post a message to the book’s errata page and fix the problem in subsequent editions of the book.

P2P.WROX.COM

For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a web-based system on which you can post messages relating to Wrox books and related technologies and interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.

At http://p2p.wrox.com you will find a number of different forums that will help you not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps:

  1. Go to p2p.wrox.com and click the Register link.
  2. Read the terms of use and click Agree.
  3. Complete the required information to join as well as any optional information you wish to provide, and click Submit.
  4. You will receive an e-mail with information describing how to verify your account and complete the joining process.

Once you join, you can post new messages and respond to messages other users post. You can read messages at any time on the Web. If you would like to have new messages from a particular forum e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.

For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works, as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page.

HOW TO READ THIS BOOK

This book is mostly designed as a hands-on tutorial and tries to keep you practicing and trying out new concepts as quickly and often as possible. As mentioned before, you will find Try It Outs throughout this book where you will find step-by-step instructions for working with Java.

You will notice that we alternate between chapters that are more theoretical in nature (such as what Object-Oriented Programming is) and chapters that are more practical (such as how to read in a file and do something with it). As such, the preferred way to go through this book when you’re reading it the first time is to work your way from beginning to end. Think of this book as a tour through Java. We do not visit every nook and cranny—you don’t need to examine each and every small detail—but you do want to get the big picture, enabling you to get proficient with Java as quickly as possible without taking dangerous shortcuts by explaining concepts in a haphazardly manner. Whenever you encounter a practical chapter that seems less useful, however, you are free to skip it and return to it later. That said, we have clearly separated the chapters to match a specific set of topics, so readers revisiting this book will have no trouble immediately navigating to the right spot.

Given the nature of programming, it is unavoidable that you will run across some examples in earlier chapters that includes a concept that will be explained in a later section. We always indicate these forward references in a clear manner and tell you “not to worry about this until Chapter X.” Trust us on this; these elements will be covered later.

As you proceed, remember the best way to learn is to try out things on your own, extend projects, and create new ones. The Try It Out exercises provide examples throughout the text for you to start programming with a lot of guidance. As your knowledge and confidence build, try creating your own simple programs to complete tasks that are interesting for you. This way, you will put the concepts you’ve learned to use and start to see how Java can work for you.

GET IN TOUCH

We have tried to make this book as complete, accurate, and enjoyable as possible. Of course, what really matters is what you, as the reader, think of it. Please let us know your views by getting in touch. The authors welcome all feedback and comments.

Bart Baesens

Aimée Backiel

Seppe vanden Broucke

January, 2015

1
A General Introduction to Programming

WHAT YOU WILL LEARN IN THIS CHAPTER:                

WROX.COM CODE DOWNLOADS FOR THIS CHAPTER

The wrox.com code downloads for this chapter are found at www.wrox.com/go/beginningjavaprogramming on the Download Code tab. The code is in the Chapter 1 download and individually named according to the names throughout the chapter.

Developing good and correct software is a very important challenge in today’s business environment. Given the ubiquity and pervasiveness of software programs into our daily lives, the impact of faulty software is now bigger than ever. Software errors have caused flight crashes, rocket launch errors, and power blackouts, to name a few examples. Hence, it is important to design high-quality, error-free software programs. This chapter covers the fundamental concepts of programming. First, it elaborates on the programming process. The next section provides a sneak preview of object-oriented programming. This is followed by a short discussion on programming errors. The basic principles of software testing and software maintenance are also discussed. The chapter concludes by giving some recommendations relating to structured programming. You will revisit many of these ideas in future chapters, with a more hands-on approach.

THE PROGRAMMING PROCESS

A program (also referred to as an application) is a set of instructions targeted to solve a particular problem that can be unambiguously understood by a computer. To this end, the computer will translate the program to the language it understands, which is machine language consisting of 0s and 1s. Computers execute a program literally as it was programmed, nothing more and nothing less. Programming is the activity of writing or coding a program in a particular programming language. This is a language that has strict grammar and syntax rules, symbols, and special keywords. People who write programs are commonly referred to as programmers or application developers. The term software then refers to a set of programs within a particular business context.

An example of a programming exercise is a program that calculates the body mass index (BMI) of a person. The BMI is calculated by dividing a person’s weight in kilograms by the square of his or her height in meters. A person is considered overweight if his or her BMI is over 25. A BMI calculator program then requires the weight and height as inputs and calculates the associated BMI as the output. This is illustrated in Figure 1.1. This BMI example is used to demonstrate the steps in the software development cycle.

images

Figure 1.1

Programs are typically written using a step-by-step approach, as follows:

  1. Requirements gathering and analysis
  2. Program design
  3. Program coding
  4. Translation to machine language
  5. Testing and debugging
  6. Deployment
  7. Maintenance

Because our environment is continuously evolving, software, too, is often continually reviewed and adapted. Therefore, these steps are often represented as a cycle, as shown in Figure 1.2, rather than as a ladder.

images

Figure 1.2

The first step is to make sure you understand the problem in sufficient detail. This means analyzing the problem statement carefully so you fully grasp all the requirements that need to be fulfilled by the software program. This may involve Q&A sessions, interviews, and surveys with business experts who have the necessary subject matter expertise. Even if you are programming for yourself, taking the time upfront to consider all the demands you want your program to meet will limit the amount of changes required later in the process. At the end of this step, it is important to know what the input to the program will receive and what output it should give. In the BMI example, you will need to know whether the height will be measured in meters or feet and the weight in kilos or pounds. You would also want to determine whether the output should be just the BMI results or also a message stating whether or not the person is overweight.

Once you have a thorough understanding of the business problem, you can start thinking about ways to solve it using a computer program. In other words, which processing steps should take place on the input(s) in order to give the desired output(s)? The procedure needed to solve the problem is also often referred to as the algorithm. When working out an algorithm, common sense and creativity both play an important role. A first useful step in designing an algorithm is planning the application logic using pseudo-code or flowcharts. Pseudo-code is a type of structured English but without strict grammar rules. It is a user-friendly way of representing application logic in a sequential, readable format. It allows the problem statement to be broken into manageable pieces in order to reduce its complexity. Following is an example of pseudo-code for the BMI case. A flowchart represents the application in a diagram, whereby the boxes show the activities and the arrows the sequences between them. Table 1.1 presents an overview of the most important flowchart construction concepts. Figure 1.3 then gives an example of a flowchart for the BMI case. Both pseudo-code and flowcharts can be used concurrently to facilitate the programming exercise. A key advantage of flowcharts when compared to pseudo-code is that they are visual and thus easier to interpret.

Table 1.1 Key Flowchart Modeling Concepts

FLOWCHART SYMBOL MEANING
images A terminator shows the start and stopping points of the program.
images An arrow shows the direction of the process flow.
images A rectangle represents a process step or activity.
images A diamond indicates a decision point in the process.
images This symbol represents a document or report.
images This rhombus represents data used as inputs/outputs to/from a process.
images This cylinder represents a database.
images

Figure 1.3

ask user: height
ask user: weight
if height = 0 or weight = 0:
error: "Incorrect input values"
return to beginning (ask height and weight)
end if
x = weight / (height * height)
message: "Your BMI is ",x

Table 1.1 is an overview of the most important flowchart modeling concepts.

A next step is to code the program in a particular programming language. The choice of the language will depend on the programming paradigm and the platform adopted (such as hardware, operating system, or network).

Once the source code of the program has been written, it will be given to a translator to translate it to machine language (0s and 1s) so that it can be executed and solve the business problem.

During application development, it is important that every program is intensively tested to avoid any errors. Often, in programming, errors are called bugs. Various types of errors exist and an entire chapter is devoted to this topic. Programming tools frequently have debugging facilities built in to easily track bugs down and correct them. It is possible to debug your program without the use of such tools, but in either case, you should follow a structured and systematic review to be sure you’ve identified any bugs before your program is deployed.

Once a program has been thoroughly tested, it can be deployed. This means that the program will be brought into production and actively used to solve the business problem. Remember, users of your software don’t usually understand as much about programming as you. Try to keep them in mind throughout the process to make this deployment step as seamless as possible.

Finally, programs should be maintained on an ongoing basis. There are many reasons for regular maintenance, namely correcting newly discovered bugs, accommodating changing user needs, preventing erroneous user input, or adding new features to existing programs.

It is important to note that programming is not a strict, sequential, step-by-step process. Quite to the contrary, it often occurs as an iterative process, whereby the original business problem is refined or even reformulated during the coding process.

OBJECT-ORIENTED PROGRAMMING: A SNEAK PREVIEW

In object-oriented (OO) programming, an application consists of a series of objects that ask services from each other. Each object is an instance of a class that contains a blueprint description of all the object’s characteristics. Contrary to procedural programming, an object bundles both its data (which determines its state) and its procedures (which determines its behavior) in a coherent way. An example of this could be a student object having data elements such as ID, name, date of birth, email address, and so on, and procedures such as registerForCourse, isPassed, and so on. A key difference between OO and procedural programming is that OO uses local data stored in objects, whereas procedural programming uses global shared data that the various procedures can access directly. This has substantial implications from a maintenance viewpoint. Imagine that you want to change a particular data element (rename it or remove it). In a procedural programming environment, you would have to look up all procedures that make use of the data element and adapt them accordingly. For huge programs, this can be a very tedious maintenance exercise. When you’re using an OO programming paradigm, you only need to change the data element in the object’s definition and the other objects can keep on interacting with it like they did before, minimizing the maintenance.

OO programming is the most popular programming paradigm currently in use. Some examples of object-oriented programming languages are Eiffel, Smalltalk, C++, and Java.

The following code example demonstrates how to implement the BMI example in Java. Contrary to the procedural programming example, it can be clearly seen that the data (weight, height, and BMI) is bundled together with the procedures (BMICalculator, calculate, and isOverweight) into one coherent class definition.

public class BMICalculator {
  private double weight, height, BMI;

  public BMICalculator( double weight, double height ){
    this.weight = weight;
    this.height = height;
  }

  public void calculate(){
    BMI = weight / (height*height);
  }

  public boolean isOverweight(){
    return (BMI > 25);
  }
}

PROGRAMMING ERRORS

A programming error is also referred to as a bug, and the procedure for removing programming errors is called debugging. Debugging usually has the following three steps:

  1. Detect that there is an error.
  2. Locate the error. This can be quite time consuming for big programs.
  3. Solve the error.

Different types of programming errors exist and are explored in the following sections.

Syntax/Compilation Errors

A syntax or compilation error refers to a grammatical mistake in the program. Examples are a punctuation error or misspelling of a keyword. These types of errors are typically caught by the compiler or interpreter, which will generate an error message. Consider the following Java example:

  public void calculate(){
    BMI = weight / (height*height),
  }

The statement that calculates the BMI should end with a semicolon (;) instead of a comma (,), according to the Java syntax rules. Hence, a syntax error will be generated and displayed. Syntax errors are usually easy to detect and solve.

Runtime Errors

A runtime error is an error that occurs during the execution of the program. Consider the following piece of Java code to calculate the BMI:

  public void calculate(){
    BMI = weight / (height*height);
  }

If the user enters a value of 0 for height, a division by zero occurs. This creates a runtime error and will likely crash during execution. Another example of a runtime error is an infinite loop into which the program enters at execution. During the design of the program, it is important to think about possible runtime errors that might occur due to bad user input, which is where the majority of bugs will originate. These errors should be anticipated as much as possible using appropriate error-handling routines, as we will discuss later.

Logic/Semantic Errors

Logic or semantic errors are the hardest to detect since the program will give an output and not generate an error. However, the output that is given is incorrect due to a formula being incorrectly programmed. Consider the BMI example again:

  public void calculate(){
    BMI = (weight*weight) / height;
  }

This routine is clearly erroneous since it calculates the BMI as (weight*weight)/height instead of weight/(height*height). These errors cannot be detected by compilers or interpreters.

PRINCIPLES OF SOFTWARE TESTING

In order to avoid software errors (and their impact), a program should be thoroughly tested for any remaining errors before it is brought into production. The main purpose of testing is verification and validation of the software build. Verification aims at answering the question as to whether the system was built correctly, whereas validation tries to determine whether the right system was built. The quicker an error is found during development, the cheaper it is to correct it. As illustrated in Figure 1.4, the cost of testing typically increases exponentially, whereas the cost of missed bugs decreases exponentially with the amount of testing conducted. The optimum testing resources can then be found where both curves intersect.

images

Figure 1.4

A first basic way of testing is to desk-check the program by using paper and pencil. The manual calculations and output can then be contrasted with the program calculations and output. It is especially important to consider extreme cases and see how the program behaves. Of course, this only works for small-scale programs; more sophisticated procedures might be needed for bigger programs.

Static testing procedures test the program not by executing it, but by inspecting and reviewing the code and performing detailed walk-throughs. It is aimed at verification. On the other hand, dynamic testing procedures test the program by executing it with carefully selected test cases. It is thus more related to validation. The test cases can be chosen according to a white box or black box strategy. In white box testing, they are selected by thorough inspection of the source code of the program; for example, by making sure all the branches in an if-then-else selection are covered, boundary conditions for loops are verified, and so on. One popular approach is to intentionally inject faults in the source code, which then need to be tracked down in a follow-up step. Black box testing considers the program as a black box and does not inspect its internal source code. One example is a procedure that tries to test all possible input parameter combinations. It is especially important to also test what happens when impossible values are entered (such as a negative value for weight and height, value of 0 for height, missing value for gender, and so on). Obviously, this becomes computationally infeasible in case many inputs are present and intelligent sampling procedures could be adopted to test as many useful input combinations as possible.

Software development typically has two phases of testing. Alpha testing is done internally by the application developers before the software is brought to the market. In beta testing, the software is given to a selected target audience and errors are reported back to the development team.

SOFTWARE MAINTENANCE

Software is always dynamically evolving, even after delivery. Maintenance is the activity of adjusting the program after it has been taken into production. This is done to boost its performance, solve any remaining errors, and/or accommodate new user requirements. Maintenance typically consumes a large part of the overall software development costs (up to 70% or more according to some estimates). This can be partly explained by the fact that much of the software people work with today is relatively old (legacy software) and has been maintained on an ongoing basis. This section covers the four main types of maintenance. They are categorized according to their intended goals.

Adaptive Maintenance

Adaptive software maintenance refers to modifying a program to accommodate changes in the environment (both hardware and software). An example of this is a new Windows release with new features added (which can also be used by the program) and old features removed (which can no longer be used by the program).

Perfective Maintenance

This refers to enhancing a program to support new or changed user requirements. Consider again the BMI example. When the user wants to be able to enter height in feet units and weight in pound units, this is a perfective maintenance operation.

Corrective Maintenance

Corrective maintenance aims at finding errors during runtime and fixing them. A further distinction can be made here between emergency fixes (which need to be solved as quickly as possible due to their critical relevance) and routine debugging (which is less urgent).

Preventive Maintenance

Preventive maintenance aims at increasing software maintainability in order to prevent future errors. A popular example here was the Y2K problem, where companies massively anticipated date calculation errors in their software programs at the end of the previous century. Another example concerns the transition of many countries from their own independent currency toward the Euro. One important activity to facilitate preventive maintenance is documentation. This means that the application is extended with various comments that are not executed by the compiler, but that indicate the meaning of the various data elements, procedures, and operations in order to facilitate future maintenance.

Among the four types of maintenance, perfective maintenance typically takes the main share of all maintenance efforts (it can even be more than 50%), followed by adaptive, corrective, and preventive maintenance.

The major causes of maintenance problems are unstructured code, lack of documentation, excessive user demand for changes, lack of user training and understanding, and high user turnover. Many organizations have standard procedures for maintenance, which typically start with the formal filing of a change request specifying the modifications needed to the software. Depending on the severity of the request and the change management strategy adopted by the organization, these change requests can be grouped and dealt with at fixed time stamps, or treated immediately.

PRINCIPLES OF STRUCTURED PROGRAMMING

To finish this introductory chapter, this section discusses some of the basic principles of structured programming.

A first important concept is stepwise refinement. Programs should be designed using a top-down strategy where the problem statement is subdivided into smaller, more manageable subproblems. These subproblems can be further broken down into smaller subproblems until each piece becomes easy to solve. This strategy should decrease the program development time and its maintenance cost.

Documentation is another important concept. It provides invaluable clarification for complex programming statements, which will again facilitate future maintenance operations. Every programming language offers facilities to include documentation lines that are ignored by the compiler or interpreter but can be easily read and understood by programmers.

Also of key importance is to assign meaningful names to programming concepts such as variables. Instead of naming a variable i or j without any explicit interpretation, it is much better to use student or course, which immediately indicate their meanings.

By incorporating these principles into your programs, you will improve your own work and at the same time make it possible for others (or even yourself—it’s not always easy to remember what you meant by varX months later) to update and continue using your software. After all, the goal is to create something useful that people will want to keep using.

That being said, let’s immerse ourselves further into the wonderful world of Java programming and continue with the next chapter!