While we are learning the Java language basics, we will be using console applications as examples to illustrate howthings work.. Once you have created the sourcecode for aprogram and sav
Trang 2Beginning Java 2, SDK 1.4 Edition
Wrox Press • • 2 0 0 3 (1156 pages)
This book outlines everything the beginning programmerneeds to know to program with the Java programminglanguage and the 1.4 Java Developer Kit With the release of JDK 1.4, programmers can look forward toachieving better performance than ever
Trang 3All rights reserved No part of this book may be reproduced, stored in a retrieval system or transmitted in any form
or by any means, without the prior written permission of the publisher, except in the case of brief quotations
embodied in critical articles or reviews
The author and publisher have made every effort in the preparation of this book to ensure the accuracy of theinformation However, the information contained in this book is sold without warranty, either express or implied.Neither the authors, Wrox Press, nor its dealers or distributors will be held liable for any damages caused or alleged
to be caused either directly or indirectly by this book
Published by Wrox Press Ltd,
Arden House, 1102 Warwick Road, Acocks Green,
Trang 4Ivor Horton Steve Baker
Robert Chang
Technical Editors Phil Powers De George
Gavin Smyth
Commissioning Editors John Timney
Chanoch Wiggers
Index Production Coordinator
Andrew Criddle
Illustrations
Trang 5Project Manager Pippa Wonson
Proof Readers Cover Design
Fiona Berryman
Agnes Wiggers
Keith Westmooreland
Cover photograph by John Wright Photography, Warwick
A Note from the Author
In all my Beginning books, my objective is to minimize what, in my judgment, are the three main hurdles the aspiring
programmer must face: getting to grips with the jargon that pervades every programming language and environment,
understanding the use of the language elements (as opposed to what they are), and appreciating how the language is
applied in a practical context
Jargon is an invaluable and virtually indispensable means of communication for the competent amateur as well as theexpert professional, so it can't be avoided My approach is to ensure that the beginner understands what the jargonmeans and gets comfortable with using it in context In that way, they can use the documentation that comes alongwith most programming products more effectively, and can also feel competent to read and learn from the literaturethat surrounds most programming languages
Comprehending the syntax and effects of the language elements are obviously essential to learning a language, but I
believe illustrating how the language features work and how they are used are equally important Rather than just use
code fragments, I always try to provide the reader with practical working examples that show the relationship of eachlanguage feature to specific problems These can then be a basis for experimentation, to see at first hand the effects ofchanging the code in various ways
The practical context needs to go beyond the mechanics of applying individual language elements To help the
beginner gain the competence and confidence to develop their own applications, I aim to provide them with an insightinto how things work in combination and on a larger scale than a simple example with a few lines of code That's why
I like to have at least one working example that builds over several chapters In that way it's possible to show
something of the approach to managing code as well as how language features can be applied together
Trang 6Finally, I know the prospect of working through a book of doorstop proportions can be quite daunting For thatreason it's important for the beginner to realize three things that are true for most programming languages First, there
is a lot to it, but this means there will be a greater sense of satisfaction when you've succeeded Second, it's great fun,
so you really will enjoy it Third, it's a lot easier than you think, so you positively will make it.
Ivor Horton
Trang 7Chapter 1: Introducing Java
of program that is applicable in each context
In this chapter you will learn:
Trang 8What 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 Internet 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 will not do anything that might interferewith the operation of your computer, or damage the data you have on your system This implies that execution of theembedded code must be controlled in such a way that it will prevent accidental damage to your computer
environment, as well as ensure that any Java code that was created with malicious intent is effectively inhibited Javaimplicitly incorporates measures to minimize the possibility of such occurrences arising with a Java applet
Java also allows you to write large-scale application programs that you can run unchanged on any computer with anoperating system environment in which the language is supported This applies to the majority of computers in usetoday You can even write programs that will work both as ordinary applications and as applets
Java has matured immensely in recent years, particularly with the introduction of Java 2 The breadth of functionprovided by the standard core Java has grown incredibly Java provides you with comprehensive facilities for buildingapplication with an interactive GUI, extensive image processing and graphics programming facilities, as well assupport for accessing relational databases and communicating with remote computers over a network Release 1.4 ofJava added a very important additional capability, the ability to read and write XML Just about any kind of
application can now be programmed effectively in Java, with the implicit plus of complete portability
Features of the Java Language
The most important characteristic of Java is that it was designed from the outset to be machine independent Javaprograms can run unchanged on any operating system that supports Java Of course there is still the slim possibility ofthe odd glitch as you are ultimately dependent on the implementation of Java on any particular machine, but Javaprograms are intrinsically more portable than programs written in other languages An application written in Java willonly require a single set of sourcecode, regardless of the number of different computer platforms on which it is run Inany other programming language, the application will frequently require the sourcecode to be tailored to
accommodate different computer environments, particularly if there is an extensive graphical user interface involved.Java offers substantial savings in time and resources in developing, supporting, and maintaining major applications onseveral 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 also an implicit feature of all Java programs, so we will be looking at what this implies later in thischapter Object-oriented programs are easier to understand, and less time-consuming to maintain and extend thanprograms that have been written without the benefit of using objects
Trang 9Not only is Java object oriented, but it also manages to avoid many of the difficulties and complications that areinherent in some other object-oriented languages, making it easy to learn and very straightforward to use It lacks thetraps and 'gotchas' that arise in some other programming languages This makes the learning cycle shorter and youneed 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 Greece orJapan, as you can for English speaking countries always 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 withautomatic adaptation to the environment in which the code executes
Trang 10Learning Java
Java is not difficult, but there is a great deal to it The language itself is fairly compact, but very powerful To be able
to program effectively in Java, however, you also need to understand the libraries that go with the language, and theseare very extensive In this book, the sequence in which you learn how the language works, and how you apply it, hasbeen carefully structured so that you can gain expertise and confidence with programming in Java through a relativelyeasy and painless process As far as possible, each chapter avoids the use of things you haven't learned about
already A consequence, though, is that you won't be writing Java applications with a graphical user interface rightaway While it may be an appealing idea, this would be a bit like learning to swim by jumping in the pool at the deepend Generally speaking, there is good evidence that by starting in the shallow end of the pool and learning how tofloat before you try to swim, the chance of drowning is minimized, and there is a high expectation that you will end up
a competent swimmer
Java Programs
As we have already noted, there are two 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 (to the command line on a PC under Windows, for example), and windowed Java applications
that can create and manage multiple windows The latter use the typical graphical user interface (GUI) mechanisms ofwindow-based programs menus, toolbars, dialogs and so on
While we are learning the Java language basics, we will be using console applications as examples to illustrate howthings work These are application that use simple command line input and output With this approach we can
concentrate on understanding the specifics of the language, without worrying about any of the complexity involved increating and managing windows Once we are comfortable with using all the features of the Java language, we'll move
on to windowed applications and applet examples
Learning Java the Road Ahead
Before starting out, it is always helpful to have an idea of where you are heading and what route you should take, solet's take a look at a brief road map of where you will be going with Java There are five broad stages you willprogress 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 andhow they work This includes such things as what object-oriented programming is all about, and how anexecutable program is created from a Java source file Getting these concepts straight at the outset will makelearning to write Java programs that much easier for you
2
Trang 11Next you will learn how statements are put together, what facilities you have for storing basic data in aprogram, how you perform calculations and how you make decisions based on the results of them These arethe nuts and bolts you need for the next stages.
3
In the third stage you will learn about classes how you define them and how you can use them This is
where you learn the object-oriented characteristics of the language By the time you are through this stageyou will have learned all the basics of how the Java language works so you will be ready to progress furtherinto how you can use it
4
In the fourth stage, you will learn how you can segment the activities that your programs carry out into
separate tasks that can execute concurrently This is particularly important for when you want to includeseveral applets in a web page, and you don't want one applet to have to wait for another to finish executingbefore it can start You may want a fancy animation to continue running while you play a game, for example,with both programs sitting in the same web page
Throughout this book we will be using 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 Ifthere 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 are uncertain how some aspect of Java that you have already covered works, don'tlook it up right away try it out Making mistakes is a great way to learn
Trang 12The Java Environment
You can run Java programs on a wide variety of computers using a range of operating systems Your Java programswill run just as well on a PC running Windows 95/98/NT/2000/XP as it will 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
hypothetical computer that is called the Java virtual machine or JVM, which is emulated inside your computer by
a program
A Java compiler converts the Java sourcecode that you write into a binary program consisting of byte codes Byte
codes are machine instructions for the Java virtual machine When you execute a Java program, a program called the
Java interpreter inspects and deciphers the byte codes 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 byte codes specify within the Java virtual machine
A Java interpreter can run standalone, or it can be part of a web browser such as Netscape Navigator or MicrosoftInternet Explorer where it can be invoked automatically to run applets in a web page
Because your Java program consists of byte codes rather than native machine instructions, it is completely insulatedfrom the particular hardware on which it is run Any computer that has the Java environment implemented will handleyour program as well as any other, and because the Java interpreter sits between your program and the physicalmachine, 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 programusing native machine instructions With present Java machine implementations, much of the performance penalty hasbeen eliminated, and in programs that are not computation intensive which is usually the case with the sort of
program you would want to include in a web page, for example you really wouldn't notice this anyway With theJVM that is supplied with the current Java 2 System Development Kit (SDK) available from the Sun web site, thereare very few circumstances where you will notice any appreciable degradation in performance compared to a
program compiled to native machine code
Java Program Development
Trang 13There are a number of excellent professional Java program development environments available, including productsfrom Sun, Borland and Symantec These all provide very friendly environments for creating and editing your
sourcecode, and compiling and debugging your programs These are powerful tools for the experienced programmer,but for learning Java using this book, I recommend that you resist the temptation to use any of these, especially if youare relatively new to programming Instead, stick to using the Java 2 SDK from Sun together with a suitable simpleeditor for creating your sourcecode The professional development systems tend to hide a lot of things you need tounderstand, and also introduce complexity that you really are better off without while you are learning These
products are intended primarily for knowledgeable and experienced programmers, so start with one when you get tothe end of the book
You can download the SDK from Sun for a variety of hardware platforms and operating systems, either directly fromthe Sun Java web site at http://java.sun.com (for Windows, Solaris, and Linux operating systems), or from sites thatyou can link to from there The SDK we are going to use is available from http://java.sun.com/j2se/1.4 For instance
a version of the SDK for Mac OS is available from http://devworld.apple.com/java/
There is one aspect of terminology that sometimes causes confusion the SDK used to be known as the JDK theJava Development kit If you see JDK this generally means the same as SDK When you install the Java 2 SDK, youwill see the old terminology survives in the name of the root directory where the SDK is installed, currently /jdk1.4
I would urge you to install the SDK even if you do use one or other of the interactive development environments thatare available The SDK provides an excellent reference environment that you can use to check out problems thatmay arise Not only that, your programs will only consist of the code that you write plus the classes from the Javalibraries that you use Virtually all commercial Java development systems provide pre-built facilities of their own tospeed development While this is very helpful for production program development, it really does get in the way whenyou are trying to learn Java
A further consideration is that the version of Java supported by a commercial Java product is not always the mostrecent This means that some features of the latest version of Java just won't work If you really do prefer to workwith a commercial Java development system for whatever reason, and you have problems with running a particularexample from the book, try it out with the SDK The chances are it will work OK
To make use of the SDK you will need a plain text editor Any editor will do as long as it does not introduce
formatting codes into the contents of a file There are quite a number of shareware and freeware editors around thatare suitable, some of which are specific to Java, and you should have no trouble locating one I find the JCreatoreditor is particularly good There's a free version and a fee version with more functionality but the free version isperfectly adequate for learning You can download a free copy from http://www.jcreator.com A good place to startlooking if you want to explore what is available is the http://www.download.com web site
Installing the SDK
You can obtain detailed instructions on how to install the SDK for your particular operating system from the Sun website, so I won't go into all the variations for different systems here However, there are a few things to watch out forthat may not leap out from the pages of the installation documentation
First of all, the SDK and the documentation are separate and you install them separately The SDK for Windows isdistributed as a exe file that you just execute to start installation The documentation for the SDK consists of a largenumber of HTML files structured in a hierarchy that are distributed in a ZIP archive You will find it easier to installthe SDK first, followed by the documentation If you install the SDK to drive C: under Windows, the directory
Trang 14structure shown in the diagram will be created
The jdk1.4 directory in the diagram is sometimes referred to as the root directory for Java In some contexts it is also referred to as the Java home directory If you want the documentation installed in the hierarchy shown above,
then you should now extract the documentation from the archive to the jdk1.4 directory This corresponds to
C:\jdk1.4 if you installed the SDK to your C: drive This will create a new subdirectory, docs, to the jdk1.4 rootdirectory, and install the documentation files in that To look at the documentation you just open the index.html filethat is in the docs subdirectory
You don't need to worry about the contents of most of these directories, at least not when you get started, but youshould add the path for the jdk1.4\bin directory to the paths defined in your PATH environment variable That wayyou will be able to run the compiler and the interpreter from anywhere without having to specify supplying the path to
it If you installed the SDK to C:, then you need to add the path C:\jdk1.4\bin A word of warning if you havepreviously installed a commercial Java development product, check that it has not modified your PATH environmentvariable to include the path to its own Java executables
If it has, when you try to run the Java compiler or interpreter, you are likely to get the versions supplied with thecommercial product rather that those that came with the SDK One way to fix this is to remove the path or paths thatcause the problem If you don't want to remove the paths that were inserted for the commercial product, you willhave to use the full path specification when you want to run the compiler or interpreter from the SDK The jre
directory contains the Java Runtime facilities that are used when you execute a Java program The classes in the Javalibraries are stored in the jre\lib directory They don't appear individually though They are all packaged up in thearchive, rt.jar Leave this alone The Java Runtime takes care of retrieving what it needs from the archive when yourprogram executes
The CLASSPATH environment variable is a frequent source of problems and confusion to newcomers to Java The
current SDK does NOT require CLASSPATH to be defined, and if it has been defined by some other Java version
or system, it is likely to cause problems Commercial Java development systems and versions of the Java
Development Kit prior to 1.2 may well define the CLASSPATH environment variable, so check to see whetherCLASSPATH has been defined on your system If it has and you no longer have whatever defined it installed, youshould delete it If you have to keep the CLASSPATH environment variable maybe because you want to keep thesystem that defined it or you share the machine with someone who needs it you will have to use a command lineoption to define CLASSPATH temporarily whenever you compile or execute your Java code We will see how to
do this a little later in this chapter
Extracting the Sourcecode for the Class Libraries
Trang 15The sourcecode for the class libraries is included in the archive src.zip that you will find in the jdk1.4 root directory.Browsing this source can be very educational, and it can also be helpful when you are more experienced with Java ingiving a better understanding of how things works or when they don't, why they don't You can extract the sourcefiles from the archive using the Winzip utility or any other utility that will unpack zip archives but be warned there's
a lot of it and it takes a while!
Extracting the contents of src.zip to the root directory \jdk1.4 will create a new subdirectory, src, and install thesourcecode in subdirectories to this To look at the sourcecode, just open the java file that you are interested in,using any plain text editor
Compiling a Java Program
Java sourcecode is always stored in files with the extension java Once you have created the sourcecode for aprogram and saved it in a java file, you need to process the source using a Java compiler Using the compiler thatcomes with the JDK, you would make the directory that contains your Java source file the current directory, and thenenter the following command:
javac -source 1.4 MyProgram.java
Here, javac is the name of the Java compiler, and MyProgram.java is the name of the program source file Thiscommand assumes that the current directory contains your source file If it doesn't the compiler won't be able to findyour source file The -source command line option with the value 1.4 here tells the compiler that you want the codecompiled with the SDK 1.4 language facilities This causes the compiler to support a facility called assertions, and wewill see what these are later on If you leave this option out, the compiler will compile the code with SDK 1.3
capabilities so if the code uses assertions, these will be flagged as errors
If you need to override an existing definition of the CLASSPATH environment variable perhaps because it has
been set by a Java development system you have installed, the command would be:
javac -source 1.4 -classpath MyProgram.java
The value of CLASSPATH follows the -classpath specification and is just a period This defines just the path to the
current directory, whatever that happens to be This means that the compiler will look for your source file or files inthe current directory If you forget to include the period, the compiler will not be able to find your source files in the
current directory If you include the -classpath command line option in any event, it will do no harm
Note that you should avoid storing your source files within the directory structure that was created for the SDK, asthis can cause problems Set up a separate directory of your own to hold the sourcecode for a program and keep thecode for each program in its own directory
Assuming your program contains no errors, the compiler generates a byte code program that is the equivalent of yoursource code The compiler stores the byte code program in a file with the same name as the source file, but with theextension class Java executable modules are always stored in a file with the extension class By default, the classfile will be stored in the same directory as the source file
The command line options we have introduced here are by no means all the options you have available for thecompiler You will be able to compile all of the examples in the book just knowing about the options we have
discussed There is a comprehensive description of all the options within the documentation for the SDK You can
also specify the -help command line option to get a summary of the standard options you can use.
If you are using some other product to develop your Java programs, you will probably be using a much more
user-friendly, graphical interface for compiling your programs that won't involve entering commands such as thatshown above The file name extensions for your source file and the object file that results from it will be just the same
Trang 16Executing a Java Application
To execute the byte code program in the class file with the Java interpreter in the SDK, you make the directorycontaining the class file current, and enter the command:
java -enableassertions MyProgram
Note that we use MyProgram to identify the program, NOT MyProgram.class It is a common beginner's mistake
to use the latter by analogy with the compile operation If you put a class file extension on MyProgram, your
program won't execute and you will get an error message:
Exception in thread "main" java.lang.NoClassDefFoundError: MyProgram/class
While the compiler expects to find the name of your source file, the java interpreter expects the name of a class,
which is MyProgram in this case, not the name of a file The MyProgram.class file contains the MyProgram class.
We will explain what a class is shortly
The enableassertions option is necessary for SDK1.4 programs that use assertions, but since we will be using
assertions once we have learned about them it's a good idea to get into the habit of always using this option You can
abbreviate the -enableassertions option to -ea if you wish
If you want to override an existing CLASSPATH definition, the option is the same as with the compiler You can also abbreviate -classpath to -cp with the Java interpreter, but strangely, this abbreviation does not apply to the
compiler Here's how the command would look:
java -ea -cp MyProgram
Trang 17Object-Oriented Programming in Java
As we said at the beginning of this chapter, Java is an object-oriented language When you use a programminglanguage that is not object oriented, you must express the solution to every problem essentially in terms of numbersand characters the basic kinds of data that you can manipulate in the language In an object-oriented language likeJava, things are different Of course, you still have numbers and characters to work with these are referred to as the
basic data types but you can define other kinds of entities that are relevant to your particular problem You solve
your problem in terms of the entities or objects that occur in the context of the problem This not only affects how aprogram is structured, but also the terms in which the solution to your problem is expressed If your problem
concerns baseball players, your Java program is likely to have BaseballPlayer objects in it; if you are producing aprogram dealing with fruit production in California, it may well have objects that are Oranges in it Apart from
seeming to be inherently sensible, object-oriented programs are usually easier to understand
In Java almost everything is an object If you haven't delved into object-oriented programming before, or maybebecause you have, you may feel this is a bit daunting But fear not Objects in Java are particularly easy So easy, infact, that we are going to start out by understanding some of the ideas behind Java objects right now In that way youwill be on the right track from the outset
This doesn't mean we are going to jump in with all the precise nitty-gritty of Java that you need for describing andusing objects We are just going to get the concepts straight at this point We will do this by taking a stroll through thebasics using the odd bit of Java code where it helps the ideas along All the code that we use here will be fully
explained in later chapters Concentrate on understanding the notion of objects first Then we can ease into thespecific practical details as we go along
So What Are Objects?
Anything can be thought of as an object Objects are all around you You can consider Tree to be a particular class
of objects: trees in general; although it is a rather abstract class as you would be hard pushed to find an actual
occurrence of a totally generic tree Hence the Oak tree in my yard which I call myOak, the Ash tree in your yardwhich you call thatDarnedTree, and a generalSherman, the well-known redwood, are actual instances of specifictypes of tree, subclasses of Tree that in this case happen to be Oak, Ash, and Redwood Note how we drop into the
jargon here class is a term that describes a specification for a collection of objects with common properties.
A class is a specification, or template expressed as a piece of program code which defines what goes to make up
a particular sort of object A subclass is a class that inherits all the properties of the parent class, but that also
includes extra specialization Of course, you will define a class specification to fit what you want to do There are noabsolutes here For my trivial problem, the specification of a Tree class might just consist of its species and its height
If you are an arboriculturalist, then your problem with trees may require a much more complex class, or more likely aset of classes, that involve a mass of arboreal characteristics
Every object that your program will use will have a corresponding class definition somewhere for objects of that type.This is true in Java as well as in other object-oriented languages The basic idea of a class in programming parallels
Trang 18that of classifying things in the real world It is a convenient and well-defined way to group things together.
An instance of a class is a technical term for an existing object of that class Ash is a specification for a type of
object and yourAsh is an object constructed to that specification, so yourAsh would be an instance of the class Ash.Once you have a class defined, then you can come up with objects, or instances of that class This raises the question
of what differentiates an object of a given class, an Ash class object say, from a Redwood object In other words,what sort of information defines a class?
What Defines a Class of Objects?
You may have already guessed the answer A class definition lists all the parameters that you need to define an object
of that particular class, at least, so far as your needs go Someone else might choose a larger or smaller set of
parameters to define the same sort of object it all depends on what you want to do with the class You will decidewhat aspects of the objects you need to include to define that particular class of object, and you will choose themdepending on the kinds of problems that you want to address using the objects of the class Let's think about aspecific class of objects
For a class Hat for example, you might use just two parameters in the definition You could include the type of hat as
a string of characters such as "Fedora" or "Baseball cap", and its size as a numeric value These parameters that
define an object of a class are referred to as instance variables or attributes of a class, or class fields The
instance variables can be basic types of data such as numbers, but they could also be other class objects For
example, the name of a Hat object could be of type String the class String defines objects that are strings of
characters
Of course there are lots of other things you could include to define a Hat if you wanted to, color for instance, whichmight be another string of characters such as "Blue" To specify a class you just decide what set of attributes suit your
needs, and those are what you use This is called data abstraction in the parlance of the object-oriented aficionado,
because you just abstract the attributes you want to use from the myriad possibilities for a typical object
In Java the definition of the class Hat would look something like:
Trang 19Java Program Structure
Let's summarize the general nature of how a Java program is structured :
A Java source file must also have the extension java
Thus your file containing the class Hat will be called Hat.java and your file containing the class BaseballPlayer musthave the file name BaseballPlayer.java
A typical program will consist of several files as illustrated in the following diagram
This program clearly majors on apparel with four of the five classes representing clothing Each source file will contain
a class definition, and all of the files that go to make up the program will be stored in the same directory The sourcefiles for your program will contain all the code that you wrote, but this is not everything that is ultimately included in
the program There will also be code from the Java standard class library, so let's take a peek at what that can do.
Java's Class Library
A library in Java is a collection of classes usually providing related facilities which you can use in your programs.The Java class library provides you with a whole range of goodies, some of which are essential for your programs towork at all, and some of which make writing your Java programs easier To say that the standard class library covers
a lot of ground would be something of an understatement so we won't be going into it in detail here, but we will belooking into how to apply many of the facilities it provides throughout the book
Since the class library is a set of classes, it is stored in sets of files where each file contains a class definition The
classes are grouped together into related sets that are called packages, and each package is stored in a separate
Trang 20directory A class in a package can access any of the other classes in the package A class in another package may
or may not be accessible We will learn more about this in Chapter 5
The package name is based on the path to the directory in which the classes belonging to the package are stored.Classes in the package java.lang for example are stored in the directory path java\lang (or java/lang under Unix) Thispath is relative to a particular directory that is automatically known by the Java runtime environment that executesyour code You can also create your own packages that will contain classes of your own that you want to reuse indifferent contexts, and that are related in some way
The SDK includes a growing number of standard packages well over 100 the last time I counted Some of thepackages you will meet most frequently are:
Package Name Description
java.lang These classes support the basic language features and the handling of arrays and
strings Classes in this package are always available directly in your programs bydefault because this package is always automatically loaded with your program
java.io Classes for data input and output operations
java.util This package contains utility classes of various kinds, including classes for managing
data within collections or groups of data items
javax.swing These classes provide easy-to-use and flexible components for building graphical user
interfaces (GUIs) The components in this package are referred to as Swingcomponents
java.awt Classes in this package provide the original GUI components (JDK1.1) as well as
some basic support necessary for Swing components
java.awt.geom These classes define 2-dimensional geometric shapes
java.awt.event The classes in this package are used in the implementation of windowed application to
handle events in your program Events are things like moving the mouse, pressing theleft mouse button, or clicking on a menu item
As noted above, you can use any of the classes from the java.lang package in your programs by default To useclasses from the other packages, you will typically use import statements to identify the names of the classes that youneed from each package This will allow you to reference the classes by the simple class name Without an importstatement you would need to specify the fully qualified name of each class from a package each time you refer to it
As we will see in a moment, the fully qualified name for a class includes the package name as well as the basic classname Using fully qualified class names would make your program code rather cumbersome, and certainly less
Trang 21readable It would also make them a lot more tedious to type in
You can use an import statement to import the name of a single class from a package into your program, or all theclass names The two import statements at the beginning of the code for the applet you saw earlier in this chapter areexamples of importing a single class name The first was:
import javax.swing.JApplet;
This statement imports the JApplet class name that is defined in the javax.swing package Formally, the name of theJApplet class is not really JApplet it is the fully qualified name javax.swing.JApplet You can only use the unqualifiedname when you import the class or the complete package containing it into your program You can still reference aclass from a package even if you don't import it though you just need to use the full class name,
javax.swing.JApplet You could try this out with the applet you saw earlier if you like Just delete the two importstatements from the file and use the full class names in the program Then recompile it It should work the same asbefore Thus the fully qualified name for a class is the name of the package in which it is defined, followed by aperiod, followed by the name given to the class in its definition
You could import the names of all the classes in the javax.swing package with the statement:
import javax.swing.*;
The asterisk specifies that all the class names are to be imported Importing just the class names that your sourcecodeuses makes compilation more efficient, but when you are using a lot of classes from a package you may find it moreconvenient to import all the names This saves typing reams of import statements for one thing We will do this withexamples of Java code in the book to keep the number of lines to a minimum However, there are risks associatedwith importing all the names in a package There may be classes with names that are identical to names you havegiven to your own classes, which would obviously create some confusion when you compile your code
Important
You will see more on how to use import statements
in Chapter 5, as well as more about how packagesare created and used, and you will be exploring theuse of classes from the standard packages inconsiderable depth throughout the book
As we indicated earlier, the standard classes do not appear as files or directories on your hard disk They are
packaged up in a single compressed file, rt.jar, that is stored in the jre/lib directory This directory is created when
you install the JDK on your computer A jar file is a Java archive a compressed archive of Java classes The
standard classes that your executable program requires are loaded automatically from rt.jar, so you don't have to beconcerned with it directly at all
Java Applications
Every Java application contains a class that defines a method called main() The name of this class is the name thatyou use as the argument to the Java interpreter when you run the application You can call the class whatever youwant, but the method which is executed first in an application is always called main() When you run your Javaapplication the method main()will typically cause methods belonging to other classes to be executed, but the simplestpossible Java application program consists of one class containing just the method main() As we shall see below, themain() method has a particular fixed form, and if it is not of the required form, it will not be recognized by the Javainterpreter as the method where execution starts
We'll see how this works by taking a look at just such a Java program You need to enter the program code using
Trang 22your favorite plain text editor, or if you have a Java development system with an editor, you can enter the code forthe example using that When you have entered the code, save the file with the same name as that used for the classand the extension java For this example the file name will be OurFirstProgram.java The code for the program is:
The program consists of a definition for a class we have called OurFirstProgram The class definition only containsone method, the method main() The first line of the definition for the method main() is always of the form:
Trang 23Java and Unicode
Programming to support languages that use anything other than the Latin character set has always been a majorproblem There are a variety of 8-bit character sets defined for many national languages, but if you want to combinethe Latin character set and Cyrillic in the same context, for example, things can get difficult If you want to handleJapanese as well, it becomes impossible with an 8-bit character set because with 8 bits you only have 256 differentcodes so there just aren't enough character codes to go round Unicode is a standard character set that was
developed to allow the characters necessary for almost all languages to be encoded It uses a 16-bit code to
represent a character (so each character occupies two bytes), and with 16 bits up to 65,535 non-zero charactercodes can be distinguished With so many character codes available, there is enough to allocate each major nationalcharacter set its own set of codes, including character sets such as Kanji which is used for Japanese, and whichrequires thousand of character codes It doesn't end there though Unicode supports three encoding forms that allow
up to a million additional characters to be represented
As we shall see in Chapter 2, Java sourcecode is in Unicode characters Comments, identifiers (names see Chapter
2), and character and string literals can all use any characters in the Unicode set that represent letters Java alsosupports Unicode internally to represent characters and strings, so the framework is there for a comprehensiveinternational language capability in a program The normal ASCII set that you are probably familiar with corresponds
to the first 128 characters of the Unicode set Apart from being aware that each character occupies two bytes, youcan ignore the fact that you are handling Unicode characters in the main, unless of course you are building an
application that supports multiple languages from the outset
Trang 24In this chapter we have looked at the basic characteristics of Java, and how portability between different computers
is achieved We have also introduced the elements of object-oriented programming There are bound to be someaspects of what we have discussed that you don't feel are completely clear to you Don't worry about it Everything
we have discussed here we will be revisiting again in more detail later on in the book
The essential points we have covered in this chapter are:
Trang 26http://java.sun.com/docs/books/tutorial/index.html for the JavaSoft tutorials Follow that Java trail.
and for online magazine reading and opinion, check out:
•
Trang 28Chapter 2: Programs, Data,
Variables, and Calculation
Overview
In this chapter we will look at the entities in Java that are not objects numbers and characters This will give you allthe elements of the language you need to perform numerical calculations, and we will apply these in a few workingexamples
By the end of this chapter you will have learnt:
Trang 29What determines the sequence in which operators in an expression are executed
•
How to include comments in your programs
Trang 30Data and Variables
A variable is a named piece of memory that you use to store information in your Java program a piece of data ofsome description Each named piece of memory that you define in your program will only be able to store data ofone particular type If you define a variable to store integers, for example, you cannot use it to store a value that is adecimal fraction, such as 0.75 If you have defined a variable that you will use to refer to a Hat object, you can onlyuse it to reference an object of type Hat (or any of its subclasses, as we saw in Chapter 1) Since the type of datathat each variable can store is fixed, whenever you use a variable in your program the compiler is able to check that it
is not being used in a manner or a context that is inappropriate to its type If a method in your program is supposed toprocess integers, the compiler will be able to detect when you inadvertently try to use the method with some otherkind of data, for example, a string or a numerical value that is not integral
Explicit data values that appear in your program are called literals Each literal will also be of a particular type: 25, forinstance, is an integer value of type int We will go into the characteristics of the various types of literals that you canuse as we discuss each variable type
Before you can use a variable you must specify its name and type in a declaration statement Before we look at howyou write a declaration for a variable, we should consider what flexibility you have in choosing a name
Variable Names
The name that you choose for a variable, or indeed the name that you choose for anything in Java, is called an
identifier An identifier can be any length, but it must start with a letter, an underscore (_), or a dollar sign ($) Therest of an identifier can include any characters except those used as operators in Java (such as +, , or *), but you will
be generally better off if you stick to letters, digits, and the underscore character
Java is case sensitive, so the names republican and Republican are not the same You must not include blanks or tabs
in the middle of a name, so Betty May is out, but you could have BettyMay or even Betty_May Note that you can'thave 10Up as a name since you cannot start a name with a numeric digit Of course, you could use tenUp as analternative
Subject to the restrictions we have mentioned, you can name a variable almost anything you like, except for twoadditional restraints you can't use keywords in Java as a name for something, and a name can't be anything that is aconstant value Keywords are words that are an essential part of the Java language We saw some keywords in the
previous chapter and we will learn a few more in this chapter If you want to know what they all are, a complete listappears in Appendix A The restriction on constant values is there because, although it is obvious why a name can't
be 1234 or 37.5, constants can also be alphabetic, such as true and false for example We will see how we specifyconstant values later in this chapter Of course, the basic reason for these rules is that the compiler has to be able todistinguish between your variables and other things that can appear in a program If you try to use a name for avariable that makes this impossible, then it's not a legal name
Clearly, it makes sense to choose names for your variables that give a good indication of the sort of data they hold If
Trang 31you want to record the size of a hat, for example, hatSize is not a bad choice for a variable name whereas qqq would
be a bad choice It is a common convention in Java to start variable names with a lower case letter and, where youhave a name that combines several words, to capitalize the first letter of each word, as in hatSize or
moneyWellSpent You are in no way obliged to follow this convention but since almost all the Java world does, ithelps to do so
Note
If you feel you need more guidance innaming conventions (and codingconventions in general) take a look at
http://www.javasoft.com/docs/codeconv/
Variable Names and Unicode
Even though you are likely to be entering your Java programs in an environment that stores ASCII, all Java sourcecode is in Unicode (subject to the reservations we noted in Chapter 1) Although the original source that you create isASCII, it is converted to Unicode characters internally, before it is compiled While you only ever need ASCII towrite any Java language statement, the fact that Java supports Unicode provides you with immense flexibility Itmeans that the identifiers that you use in your source program can use any national language character set that isdefined within the Unicode character set, so your programs can use French, Greek, or Cyrillic variable names, forexample, or even names in several different languages, as long as you have the means to enter them in the first place.The same applies to character data that your program defines
Variables and Types
As we mentioned earlier, each variable that you declare can store values of a type determined by the data type ofthat variable You specify the type of a particular variable by using a type name in the variable declaration Forinstance, here's a statement that declares a variable that can store integers:
Trang 32Integer Data Types
There are four types of variables that you can use to store integer data All of these are signed, that is, they can storeboth negative and positive values The four integer types differ in the range of values they can store, so the choice oftype for a variable depends on the range of data values you are likely to need
The four integer types in Java are:
Data Type Description
byte Variables of this type can have values from -128 to +127 and occupy 1 byte (8 bits) in memory
short Variables of this type can have values from -32768 to 32767 and occupy 2 bytes (16 bits) in
memory
int Variables of this type can have values from -2147483648 to 2147483647 and occupy 4 bytes
(32 bits) in memory
long Variables of this type can have values from -9223372036854775808 to
9223372036854775807 and occupy 8 bytes (64 bits) in memory
Let's take a look at declarations of variables of each of these types:
Trang 33Floating Point Data Types
Numeric values that are not integral are stored as floating point numbers A floating point number has a fixed number
of digits of accuracy but with a very wide range of values You get a wide range of values, even though the number ofdigits is fixed, because the decimal point can "float" For example the values 0.000005, 500.0, and
5000000000000.0 can be written as 5x10-6, 5x102, and 5x1012 respectively we have just one digit '5' but wemove the decimal point around
There are two basic floating point types in Java, float and double These give you a choice in the number of digitsprecision available to represent your data values, and in the range of values that can be accommodated:
Data Type Description
float Variables of this type can have values from -3.4E38 (-3.4x1038) to +3.4E38 (+3.4x1038) and
occupy 4 bytes in memory Values are represented with approximately 7 digits accuracy
double Variables of this type can have values from -1.7E308 (-1.7x10308) to +1.7E308
(+1.7x10308) and occupy 8 bytes in memory Values are represented with approximately 17digits accuracy The smallest non-zero value that you can have is roughly (4.9x10-324
Important
All floating point operations and the definitions forvalues of type float and type double in Java conform
to the IEEE 754 standard
As with integer calculations, floating point calculations in Java will produce the same results on any computer
Floating Point Values
When you are specifying floating point literals they are of type double by default, so 1.0 and 345.678 are both oftype double When you want to specify a value of type float, you just append an f, or an F, to the value, so 1.0f and345.678F are both constants of type float If you are new to programming it is important to note that you must notinclude commas as separators when specifying numerical values in your program code Where you might normallywrite a value as 99,786.5, in your code you must write it without the comma, as 99786.5
When you need to write very large or very small floating point values, you will usually want to write them with anexponent that is, as a decimal value multiplied by a power of 10 You can do this in Java by writing the number as adecimal value followed by an E, or an e, preceding the power of 10 that you require For example, the distance fromthe Earth to the Sun is approximately 149,600,000 kilometers, more conveniently written as 1.496E8 Since the E
Trang 34(or e) indicates that what follows is the exponent, this is equivalent to 1.496x108 At the opposite end of the scale,the mass of an electron is around 0.0000000000000000000000000009 grams This is much more convenient, not
to say more readable, when it is written as 9.0E-28 grams
Declaring Floating Point Variables
You declare floating point variables in a similar way to that we've already used for integers We can declare andinitialize a variable of type double with the statement:
Trang 35Arithmetic Calculations
You store the result of a calculation in a variable by using an assignment statement An assignment statement consists
of a variable name followed by an assignment operator, followed by an arithmetic expression, followed by a
semicolon Here is a simple example of an assignment statement:
Trang 36Mixed Arithmetic Expressions
You can mix values of the basic types together in a single expression The way mixed expressions are treated isgoverned by some simple rules that apply to each operator in such an expression The rules, in the sequence in whichthey are checked, are:
If either operand is of type long, the other is converted to long before the operation is carried out
The first rule in the sequence that applies to a given operation is the one that is carried out If neither operand isdouble, float, or long, they must be int, short, or byte, so they use 32-bit arithmetic as we saw earlier
Explicit Casting
It may well be that the default treatment of mixed expressions listed above is not what you want For example, if youhave a double variable result, and you compute its value using two int variables three and two with the values 3 and 2respectively, with the statement:
Trang 37The op= Operators
The op= operators are used in statements of the form:
Trang 38Mathematical Functions and Constants
Sooner or later you are likely to need mathematical functions in your programs, even if it's only obtaining an absolutevalue or calculating a square root Java provides a range of methods that support such functions as part of thestandard library stored in the package java.lang, and all these are available in your program automatically
The methods that support various additional mathematical functions are implemented in the class Math as staticmethods, so to reference a particular function you can just write Math and a period in front of the name of themethod you wish to use For example, to use sqrt(), which calculates the square root of whatever you place betweenthe parentheses, you would write Math.sqrt(aNumber) to produce the square root of the floating point value in thevariable aNumber
The class Math includes a range of methods for standard trigonometric functions These are:
Method Function Argument Type Result Type
asin(arg) sin-1 (arc sine) of the
Trang 39expression that produces a value of the required type If you are not familiar with these trigonometric operations youcan safely ignore them
You also have a range of useful numerical functions that are implemented in the class Math These are:
Method Function Argument type Result type
abs(arg) Calculates the absolute value of
max (arg1,arg2) Returns the larger of the two
arguments, both of the same type
int, long, float, ordouble
The same type as theargument
min (arg1,arg2) Returns the smaller of the two
arguments, both of the same type
int, long, float, ordouble
The same type as theargument
ceil(arg) Returns the smallest integer that
is greater than or equal to theargument
floor(arg) Returns the largest integer that is
less than or equal to the argument
round(arg) Calculates the nearest integer to
the argument value
float or double Of type int for a float
argument, of type longfor a double argument
rint(arg) Calculates the nearest integer to
the argument value
IEEEremainder (arg1,arg2) Calculates the remainder when
arg1 is divided by arg2
Both of type double Of type double
The IEEEremainder()method produces the remainder from arg1 after dividing arg2 into arg1 the integral number oftimes that is closest to the exact value of arg1/arg2 This is somewhat different from the remainder operator Theoperation arg1 % arg2 produces the remainder after dividing arg2 into arg1 the integral number of times that does notexceed the absolute value of arg1 In some situations this can result in markedly different results For example,executing the expression 9.0 % 5.0 results in 4.0, whereas the expression Math.IEEEremainder(9.0,5.0) results in 1.0 You can pick one approach to calculating the remainder or the other, to suit your requirements
Where more than one type of argument is noted in the table, there are actually several methods, one for each type ofargument, but all have the same name We will see how this is possible in Java when we look at implementing class
Trang 40methods in Chapter 5.
The mathematical functions available in the class Math are:
Method Function Argument Type Result Type
sqrt(arg) Calculates the square root of the
argument
pow (arg1,arg2) Calculates the first argument raised
to the power of the second argumentarg1arg2
Both double double
exp(arg) Calculates e raised to the power of
the argument earg
log(arg) Calculates the natural logarithm
(base e) of the argument
random() Returns a pseudo-random number
greater than or equal to 0.0 and lessthan 1.0
The toRadians()method in the class Math will convert a double argument that is an angular measurement in degrees toradians There is a complementary method, toDegrees(), to convert in the opposite direction The Math class also
defines double values for e and (, which you can access as Math.E and Math.PI respectively
Let's try out a sample of the contents of the class Math in an example to make sure we know how they are used
Try It Out The Math Class
The following program will calculate the radius of a circle in feet and inches, given that it has an area of 100 squarefeet: