Read an Excerpt
Ivor Horton's Beginning Java
By Ivor Horton
John Wiley & SonsCopyright © 2011 John Wiley & Sons, Ltd
All right reserved.
Chapter OneIntroducing Java
WHAT YOU WILL LEARN IN THIS CHAPTER:
* The basic characteristics of the Java language
* How Java programs work on your computer
* Why Java programs are portable between different computers
* The basic ideas behind object-oriented programming
* How a simple Java program looks and how you can run it using the Java Development Kit
* What HTML is and how to use it to include a Java program in a web page
This chapter should give you an appreciation of what the Java language is all about. Understanding the details of what I discuss in this chapter is not important at this stage; you see all of the topics again in greater depth in later chapters of the book. The intent of this chapter is to introduce you to the general ideas that underpin what I cover through the rest of the book, as well as the major contexts in which Java programs can be used and the kind of program that is applicable in each context.
WHAT IS JAVA ALL ABOUT?
Java is an innovative programming language that has become the language of choice for programs that need to run on a variety of different computer systems. First of all, Java enables you to write small programs called applets. These are programs that you can embed in web pages to provide some intelligence. Being able to embed executable code in a web page introduces a vast range of exciting possibilities. Instead of being a passive presentation of text and graphics, a web page can be interactive in any way that you want. You can include animations, games, interactive transaction processing—the possibilities are almost unlimited.
Of course, embedding program code in a web page creates special security requirements. As an Internet user accessing a page with embedded Java code, you need to be confident that it won't do anything that might interfere with the operation of your computer or damage the data you have on your system. This implies that execution of the embedded code must be controlled in such a way that it prevents accidental damage to your computer environment, as well as ensure that any Java code that was created with malicious intent is effectively inhibited. Java implicitly incorporates measures to minimize the possibility of such occurrences arising with a Java applet.
Java's support for the Internet and network-based applications generally doesn't end with applets. For example, Java Server Pages (JSP) provides a powerful means of building a server application that can dynamically create and download HTML pages to a client that are precisely customized for the specific request that is received. Of course, the pages that are generated by JSP can themselves contain Java applets.
Java also enables you to write large-scale application programs that you can run unchanged on any computer with an operating system environment in which Java is supported. This applies to the majority of computers in use today. The slogan that was coined to illustrate the cross-platform capability of Java, "write once, run anywhere," has been amply demonstrated to be the case. You can develop code on a PC and it will run on a Java-enabled cell phone. You can even write programs that work both as ordinary applications and as applets.
Java has matured immensely in recent years. The breadth of function provided by the standard core Java has grown incredibly. Java provides you with comprehensive facilities for building applications with an interactive graphical user interface (GUI), extensive image processing and graphics programming facilities, as well as support for XML, accessing relational databases and communicating with remote computers over a network. Just about any kind of application can now be programmed effectively in Java, with the implicit plus of complete portability.
Of course, Java is still developing and growing. The latest Java Development Kit, JDK 7, adds many new facilities that include new language features as well as significant additions to the supporting libraries. You learn about all of these in this book.
FEATURES OF THE JAVA LANGUAGE
The most important characteristic of Java is that it was designed from the outset to be machine independent. You can run Java programs unchanged on any machine and operating system combination that supports Java. Of course, there is still the slim possibility of the odd glitch, as you are ultimately dependent on the implementation of Java on any particular machine, but Java programs are intrinsically more portable than programs written in other languages. An application written in Java only requires a single set of source code statements, regardless of the number of different computer platforms on which it is run. In any other programming language, the application frequently requires the source code to be tailored to accommodate different computer environments, particularly if an extensive graphical user interface is involved. Java offers substantial savings in time and resources in developing, supporting, and maintaining major applications on several different hardware platforms and operating systems.
Possibly the next most important characteristic of Java is that it is object-oriented. The object-oriented approach to programming is an implicit feature of all Java programs, so you find out what this means later in this chapter. Object-oriented programs are easier to understand and less time-consuming to maintain and extend than programs that have been written without the benefit of using objects.
Not only is Java object-oriented, but it also manages to avoid many of the difficulties and complications that are inherent in some object-oriented languages, making it easy to learn and very straightforward to use. By and large, it lacks the traps and "gotchas" that arise in some other programming languages. This makes the learning cycle shorter, and you need less real-world coding experience to gain competence and confidence. It also makes Java code easier to test.
Java has a built-in ability to support national character sets. You can write Java programs as easily for use in Greece or Japan as you can for English-speaking countries, assuming you are familiar with the national languages involved, of course. You can even build programs from the outset to support several different national languages with automatic adaptation to the environment in which the code executes.
Java is not difficult to learn, but there is a great deal to it. Although the Java language is very powerful, it is fairly compact, so acquiring an understanding of the Java language should take less time than you think. However, there's much more to Java than just the language. To be able to program effectively in Java, you need to understand the libraries that go with the language, and these are very extensive. It is also important to become familiar with open source projects, especially those developed by the Apache folks.
In this book, the sequence in which you learn how the language works and how you apply it has been carefully structured so that you gain expertise and confidence with programming in Java through a relatively easy and painless process. As far as possible, each chapter avoids the use of things that you haven't learned about already. A consequence, though, is that you won't be writing Java applications with application windows and a Graphical User Interface (GUI) right away. Although it may be an appealing idea, this would be a bit like learning to swim by jumping in the pool at the deep end. Generally speaking, there is good evidence that by starting in the shallow end of the pool and learning how to float before you try to swim, you minimize the chance of drowning, and there is a high expectation that you can end up being a competent swimmer.
As I have already noted, there are two basic kinds of programs you can write in Java. Programs that are to be embedded in a web page are called Java applets, and normal standalone programs are called Java applications. You can further subdivide Java applications into console applications, which only support character output to your computer screen (console output typically goes to the command line on a PC under Microsoft Windows, for example), and windowed applications, which can create and manage multiple windows. The latter use the typical GUI mechanisms of window-based programs—menus, toolbars, dialogs, and so on.
While you are learning the Java language basics, you use console applications as examples to understand how things work. These are applications that use simple command-line input and output. With this approach you can concentrate on understanding the specifics of the language without worrying about any of the complexity involved in creating and managing windows. After you are comfortable with using all the features of the Java language, you move on to window-based applications and applet examples.
Learning Java—the Road Ahead
Before starting out on any journey, it is always helpful to have an idea of where you're heading and what route you should take, so let's take a look at a brief road map of where you're going with Java. There are seven broad stages you progress through in learning Java using this book:
1. The first stage is this chapter. It sets out some fundamental ideas about the structure of Java programs and how they work. This includes such things as what object-oriented programming is all about and how an executable program is created from a Java source file. Getting these concepts straight at the outset makes learning to write Java programs that much easier for you.
2. Next, in Chapters 2 to 4, I explain how statements are put together, what facilities you have for storing basic data in a program, how you perform calculations, and how you make decisions based on the results of them. These are the nuts and bolts you need for the next stages.
3. In the third stage, in Chapters 5 and 6, you learn about classes—how you define them and how you can use them. Classes are blueprints for objects, so this is where you learn the object-oriented characteristics of Java. By the time you are through this stage, you should have learned all the basics of how the Java language works so you are ready to progress further into how you can apply it.
4. In the fourth stage, in Chapters 7 through 12, you learn how you deal with errors and how you read and write files. Of course, file input/output is an essential capability in the majority of applications.
5. The fifth stage is covered by Chapters 13 to 15. These chapters explain how you define generic class types, which are blueprints for creating sets of similar classes. You also learn about a range of utility classes and capabilities from the support libraries that you can apply in many different program contexts.
6. In the sixth stage, in Chapters 16 to 21, you learn in detail how you implement applications or applets with a graphical user interface, and how you handle interactions with the user in this context. This amounts to applying the GUI capabilities provided by the Java class libraries. You also learn how you manage concurrent threads of execution within a Java program, which is fundamental to effective GUI programming. When you finish this stage, you should be equipped to write your own fully fledged applications and applets in Java.
7. In the last stage you learn about the Extensible Markup Language, XML, which is a powerful tool for representing data that is to be transferred from one computer to another. You apply the Java support classes for XML in a practical context, writing and reading XML files.
At the end of the book, you should be a knowledgeable Java programmer. The rest is down to experience.
Throughout this book I use complete examples to explore how Java works. You should create and run all of the examples, even the simplest, preferably by typing them in yourself. Don't be afraid to experiment with them. If there is anything you are not quite clear on, try changing an example around to see what happens, or better still—write an example of your own. If you're uncertain how some aspect of Java that you have already covered works, don't look it up right away—try out a few things and see if you can figure it out. Making mistakes is a very effective way to learn.
THE JAVA ENVIRONMENT
You can execute Java programs on a variety of computers using a range of operating systems. Your Java programs run just as well on a PC running any supported version of Microsoft Windows as it does on Linux or a Sun Solaris workstation. This is possible because a Java program does not execute directly on your computer. It runs on a standardized environment called the Java 2 Platform that has been implemented as software in the form of the Java Runtime Environment (JRE) on a wide variety of computers and operating systems. The Java Platform consists of two elements—a software implementation of a hypothetical computer called the Java Virtual Machine (JVM) and the Java Application Programming Interface (Java API), which is a set of software components that provides the facilities you need to write a fully fledged interactive application in Java.
A Java compiler converts the Java source code that you write into a binary program consisting of bytecodes. Bytecodes are machine instructions for the JVM. When you execute a Java program, a program called the Java interpreter inspects and deciphers the bytecodes for it, checks it out to ensure that it has not been tampered with and is safe to execute, and then executes the actions that the bytecodes specify within the JVM. A Java interpreter can run standalone, or it can be part of a web browser such as Google Chrome, Mozilla Firefox, or Microsoft Internet Explorer where it can be invoked automatically to run applets in a web page.
Because your Java program consists of bytecodes rather than native machine instructions, it is completely insulated from the particular hardware on which it is run. Any computer that has the Java environment implemented handles your program as well as any other, and because the Java interpreter sits between your program and the physical machine, it can prevent unauthorized actions in the program from being executed.
In the past, there has been a penalty for all this flexibility and protection in the speed of execution of your Java programs. An interpreted Java program would typically run at only one-tenth of the speed of an equivalent program using native machine instructions. With present Java machine implementations, much of the performance penalty has been eliminated, and in programs that are not computation intensive—you really wouldn't notice this anyway. With the JVM that is supplied with the current Java 2 Development Kit (JDK) available from the Oracle website, there are very few circumstances where you notice any appreciable degradation in performance compared to a program compiled to native machine code.
Java Program Development
For this book you need the Java 2 Platform, Standard Edition (J2SE) version 7 or later. The JDK is available from www.oracle.com/technetwork/java/javase/downloads/index.html. You can choose from versions of the JDK for Solaris, Linux, and Microsoft Windows, and there are versions supporting either 32-bit or 64-bit operating system environments.
Using a Program Code Editor
To create the Java program source files that you use with the JDK, you need some kind of code editor. There are several excellent professional Java program development tools available that provide friendly environments for creating and editing your Java source code and compiling and debugging your programs. These are powerful tools for the experienced programmer that improve productivity and provide extensive debugging capabilities. However, for learning Java using this book, I recommend that you resist the temptation to use any of these for the time being.
Excerpted from Ivor Horton's Beginning Java by Ivor Horton Copyright © 2011 by John Wiley & Sons, Ltd. Excerpted by permission of John Wiley & Sons. All rights reserved. No part of this excerpt may be reproduced or reprinted without permission in writing from the publisher.
Excerpts are provided by Dial-A-Book Inc. solely for the personal use of visitors to this web site.