Prentice Hall Just Java 2 6th Edition Jul 2004 ISBN 0131482114
• Just Java™ 2 SIXTH EDITION
By
PETER van der LINDEN
Publisher : Addison Wesley Pub Date : June 21, 2004
ISBN : 0-13-148211-4 Pages : 848
The #1 introduction to J2SE 1.5 and enterprise/server-side development!
An international bestseller for eight years,
Just Java(TM) 2 is the complete, accessible
Java tutorial for working programmers at all levels. Fully updated and revised, this sixth
edition is more than an engaging overview of
Java 2 Standard Edition (J2SE 1.5) and its libraries: it's also a practical introduction to today's best enterprise and server-sideprogramming techniques. Just Java(TM) 2,
Sixth Edition, reflects both J2SE 1.5 and the latest Tomcat and servlet specifications
Extensive new coverage includes: New chapters on generics and enumerated types New coverage of Web services, with practical examples using Google and Amazon Web services Simplified interactive I/O with printf() Autoboxing and unboxing of primitive types Static imports, foreach loop construct, and other new language features Peter van der Linden delivers expert advice, clear explanations, and crisp sample
programs throughoutincluding dozens new to
this edition. Along the way, he introduces:The core language: syntax, objects, interfaces, nested classes, compiler secrets, and much more
Key libraries: date and calendar, pattern matching, network software, mapped I/O, utilities and generic collections Server-side technology: network server systems, a complete tiny HTML Web server, and XML in Java Enterprise J2EE: Sql and JDBC(TM)
tutorial, servlets and JSP and much more
Client-side Java: fundamentals ofJFC/Swing GUI development, new class
data sharing detailsCompanion Web Site
All the book's examples and sample programs
are available at http://afu.com.• Just Java™ 2 SIXTH EDITION
By
PETER van der LINDEN
Publisher : Addison Wesley Pub Date : June 21, 2004
ISBN : 0-13-148211-4 Pages : 848
Copyright © 2004 Sun Microsystems, Inc
Printed in the United States of America. 4150 Network Circle, Santa Clara, California 95054 U.S.A.
Library of Congress Control Number: 2004107483 All rights reserved. This product and related documentation are protected by copyright and distributed under licenses restricting its use, copying, distribution, and decompilation. No part of this product or related documentation may be reproduced in any form by any means without prior written authorization of Sun and its licensors, if any.
RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by the United States Government is subject to the restrictions set forth in DFARS 252.227-7013 (c)(1)(ii) and FAR 52.227-19. The products described may be protected by one or more U.S. patents, foreign patents, or pending applications. TRADEMARKSHotJava, Java, Java Development Kit, J2EE, JPS, JavaServer Pages, Enterprise JavaBeans, EJB, JDBC, J2SE, Solaris, SPARC, SunOS, and Sunsoft are trademarks of Sun Microsystems, Inc. All other products or services mentioned in this book are the trademarks or service marks of their respective companies or organizations.
Prentice Hall PTR offers excellent discounts on this book
when ordered in quantity for bulk purchases or special sales. For more information, please contact U.S. Corporate and Government Sales, 1-800-382-3419, For sales outside of the U.S., please contact International Sales, 1-317-581- 3793,Acquisitions Editor: Gregory G. Doench Editorial Assistant: Raquel Kaplan Production Supervision: Julie B. Nahil Editor: Solveig Haugland Cover Designer: Nina Scuderi Art Director: Gail Cocker-Bogusz Manufacturing Manager: Carol Melville Marketing Manager: Chris Guzikowski Sun Microsystems Press Publisher: Myrna Rivera
Text printed on recycled paper 1 2 3 4 5 6 7 8 9 10CRW0807060504 First printing, June 2004
Dedication
I used to dedicate these books to specific brands of real ale; it
was always good for lunch with the chairman when I toured the
brewery. Here's something different. I've worked in the computer industry all my life, and in the last few years startedteaching programming classes too. You learn a lot when you get
immediate feedback about topics that need to be expressed in easier pieces. I would like to dedicate this book to all mystudents past and present, and all my teachers, young and old.
Preface
The first edition of Just Java was one of the earliest books to accompany the original release of Java in 1996. The launch of Java coincided with the explosion of interest in the web and the net which, in turn, drove technology forward at a frantic pace. People talked about "Internet time," which meant three things to me in Silicon Valley: there was immense pressure to rapidly create new hardware and software products; everyone wrote software to display stock prices on their desktops and cell phones; you were forgiven for not showering if you fell asleep at your desk after midnight and woke up there the next morning. Times have changed, but software productivity remains a big reason behind Java's popularity.
Over the last eight years Java has had six major releases, averaging one about every 18 months. With each of these releases, there has been a new edition of Just Java to describe and explain the technology. shows how the language and libraries have improved.
Table 1. Java changes from JDK 1.0.2 to Java 2 v1.4 See Just Java 6th Release Date Content ed.
JDK 1.0.2 Jan 1996 First general release of Throughout the book the language and libraries Language changes:
JDK 1.1 Feb 1997 Instance initializers
Library changes: Delegation based
event-handlers
I/O Readers andJDK 1.2 Dec 1998 Language changes: (rebadged to Java 2) strictfp
JDBC enhancements Thread local storage
Java 2 v1.3 May 2000 Performance and bug Throughout the book fixes, no significant changes
Java 2 v1.4 Dec 2001 Language changes: Assert statement
attempt) This is a remarkable pace of development for a programming system, particularly when Sun keeps such an emphasis on backward compatibility and portability. The Java 1.2 release was a significant one, bundling major functionality improvements like the collection classes and the Swing GUI library. Java 1.3 and 1.4 were comparatively smaller, although 1.4 did bring a new statement ("assert") into the language. Two and a half years in the making, Java 1.5 is the biggest version yet. It is bigger and more significant than JDK 1.2. Sun will probably rename Java 1.5 to some awkward and confusing name using two sets of numbers, like "Java 2 Mega-edition v1.5 fab-o-lux". Whatever they call it, think of Java 1.5 as "Java 3".
shows some of the substantial language additions.
Table 2. Java 2 v1.5 Release Date Content See Just Java 6th ed.
Java 2 Jun 2004 Language changes: v1.5 Autoboxing and unboxing
Variable-arity methods
Library changes: printf (like C's printf)
java.util.scanner (fourth attempt at fixing I/O)
java.util.concurrent thread utilities
javax.xml XML support bundled
Class data sharing
Can add Swing components directly to a Container!
There are also the traditional bug-fix, library and performance
improvements, including some exciting optimizations for desktop applications. Over the years, I've put a lot of hard work into unlocking the changes in Java, so you don't have to. You're looking at the results of that effort: the sixth edition of Just Java. I'm confident you'll find it easy to read, and packed with the information you need. I hope that you'll want a copy for yourself. But if not, I want you to put it back on the shelf, only (as my friend Alan Abel suggested) in a more prominent position.
P.
Acknowledgments
I'm very grateful to the following people, who are some of the most talented and creative individuals you'll find: Gilad Bracha Michael Davidson Jane Erskine Marcus Green Roedy Green Trey Harris Karsten Lentzsch Bob Lynch Aleksander Malinowski Simon Roberts Rick Ross, who provides first-class leadership at
Kerry Shetline Robin Southgate Lefty Walkowiak All the cowboys and cowgirls down on the Java Ranch
The Limewire team
The unsung heroes and heroines of Sun's Java and Solaris groups The editorial, marketing, and production teams at Prentice-Hall and Sun Microsystems deserve full appreciation: Greg Doench, Chris Guzikowski, Julie Nahil, Raquel Kaplan, Nina Scuderi, and Solveig Haugland and her magic editing pixies. Thanks too, to my wife, family, and friendshey, if I wanted my study to look organized, I'd keep it that way, OK?
Part 1: Language
Chapter 1. What Can Java Do for Me? What Java Does for You Why Portability Matters Language and Libraries One Size Doesn't Fit All Some Light ReliefA Java Desktop Application Java has become a very popular programming language for the
kind of modern software people want to write. Java began as a research project inside Sun Microsystems. The results were posted on the web, and Java took off like a Titan rocket. Sun wisely decided to nurture the market by sharing, and licensed the technology across the computer industry. Today, Java compilers and source code are available for free download from many different organizations. Just about the entire computer industry is backing Java enthusiastically with products and support. In this chapter we'll look at the reasons behind Java's popularity, and summarize the key features of the language.
Java works well for web and server-based applications. It has great features like object-oriented programming, easy database access, and well-designed GUI support. The latest release, Java 2 version 1.5, has performance tweaks to speed up desktop programs. There are libraries for communicating across networks, and for encryption. It has strong security built in. Most programmers pick up Java quickly. Behind all this, Java is more than just the latest, most popular programming language. It is a way of creating applications that are independent of all hardware and all operating systems.
What Java Does for You: Software Portability
What is meant by "applications that are independent of all hardware and operating systems?" It means you can compile a Java program on any system and run the resulting binary executable file on the same or any other systemon a Macintosh, on Windows 98, NT, 2K, XP, on Solaris, Linux, BSD or any of the varieties of Unix, on IBM's mainframe operating systems, on cell phones, Personal Digital Assistants (PDAs), embedded processors, and even on smart cards (credit cards with a microprocessor and memory), as shown in .
Figure 1-1. Future-proof software: Your Java
application runs on every system. No more
"requires Windows XP" or "Linux PPC only" , or
"compiled for MacOS X version 10.5"; just "built
with Java," and you're done.
[View full size image]
You will even be able to run on future operating system releases, like Microsoft's Longhorn. Java will be ported to all future operating systems of significance. It's also a fast way for new hardware to get software applications that will run on it.
Java unlocks software from being coupled to any specific OS and hardware platform. This new flexibility has made Java very popular with users, IT departments, and software vendors. All three benefit enormously from software portability.
Why Portability Matters
You might think that software portability does not affect you: your application software runs fine on your PC today and that's all you use. And that's true, right up until the time you want to consider a new or different system.
Say you're in the market to buy a new desktop system, and a friend shows you the video-editing, music, virus resistance, and digital picture capabilities of his Apple Macintosh. You consider switching to a Mac. Switching GUIs is a no-brainerGUIs all do essentially the same things, and it only takes a day or two to re-train your fingers. The problem is the apps. You are faced with the "choice" of walking away from your investment in your existing PC-only software, or buying yet another Windows PC that has some compatibility with your previous system. You can easily switch hardware from Dell to H-P or IBM, but there's a software barrier to switching from Windows to something with fewer security problems, like Linux or MacOS. You've been locked in. When your application programs are written in Java, you can upgrade OS and applications independently. You can try Linux and still use your familiar applications. You can move your existing Java programs to any new system, and carry on using them. This is why software portability matters to home users. For businesses, the problem is worse and far more expensive. Even if your whole organization has standardized on, say, Microsoft Windows XP, there have been numerous releases over just the last decade and a bit: MS-DOS, Win 3.1, Win3.11, Win95A, Win95B, Win98, 98 SE, ME, NT 3.1, NT3.5, NT3.51, NT4, 2K, multiple service packs and required hot-fixes, XP, and Longhorn on the horizon. These platforms have subtle and different incompatibilities amongthem. Even applications running on a single platform have limited interoperability. Older versions of Microsoft Office cannot read files produced by default from the latest Microsoft Office, even when the files don't use any of the new features. This is done deliberately, to force upgrades. If even one person in an office upgrades, everyone has to (or risk being cut off from reading new files). Software portability is all about "future-proofing" your software investment. Rewrite it in Java, and that's the last port you'll ever need to do. Portability is the Holy Grail of the software industry. It has long been sought, but never before attained. Java brings the industry closer to true software portability than any previous system has.
Software portability for office applications
There is today an excellent alternative to costly and incompatible MS Office updates. You can download the free OpenOffice.orgsoftware and use it instead of MS Office. MS Office Professional Edition 2003 costs $499 in the USA for the basic productfor one computer. OpenOffice.org has the same look and features, and is free for any number of computers. OpenOffice.org can read and save files in MS Office formats. You can even get the source code. Over twenty million users have downloaded it, and you can get your copy at:
There are OpenOffice.org versions available for Linux, Windows, MacOS, and Solaris, in many different national languages. OpenOffice.org is not written in Java, so it needs an executable for each platform. OpenOffice.org (like Java) is based on source code made freely available from Sun. There is a programmers guide and SDK at
Java and jobs
Software portability has a wonderful side-effect: skills portability for programmers. Many companies today are out- sourcing programming jobs to countries with low direct labor costs. It's a short-term cost-saving that looks good on paper, until you look at the wider implications. The beneficiaries of jobs exported from the West are Asian countries with poor performance in the annual global survey of corruption (see ). It's a risky long-term widespread corruption, unproven business privacy and intellectual property laws, with scant free market experience, and no effective environmental or workplace regulation. The bigger picture needs to be thought through when choosing to export jobs and assets from our home economies. As people with a stake in the computer industry, we have a duty to make our views (whatever they are) known to politicians. Looking at this another way, China (a nation of 1.3 billion) has already standardized on Linux, and India (1 billion people) is reviewing it. Java offers the only viable way to create software targeted at both the West and at emerging markets.
If you're a programmer in the USA or Western Europe affected by jobs moving offshore, Java is a big plus for your career. Employers used to advertise for very specific hardware and OS experience ("must have 2 years of MVS on OS/390") and ignore other resumes. Today, your Java experience gained on any OS is directly transferable to other hardware and jobs.
Java is in demand by employers. An April 2004 review of one of the US's largest job sites reflected these hiring needs. Microsoft's C# was mentioned in about 1400 postings, while C++ was a requirement in about 4000 postings. That's what you would expect. C++ is much more widespread than C#, and runs on many more computers. But Java was a surprise: more than 6800 postings sought Java skills. More employers wanted Java experience than those who wanted C++ and C# combined. This is just an anecdotal datapoint, but it is consistent with other surveys. The Software Development Times paper reported in December 2003 that nearly three-quarters of enterprise software development managers are using Java and another 11% plan to start in the next year. Investing some of your time in Java is good for your career.
Java and Microsoft
Java portability poses a real threat to Microsoft's monopoly. Software that can run on any operating system has a larger market than software that is limited to Windows only. Over time
ISVs will move their products away from Windows-only to Javaunless Java can somehow be spoiled or broken. It is unfortunate for you, me, and all computer users that Microsoft uses its monopoly to try to undermine Java. At first, Microsoft introduced deliberate incompatibilities into the Java product it licensed from Sun. Microsoft paid $20Mto Sun to settle the resulting court case. In April 2004, Microsoft paid Sun a further $1.9 billion to settle Sun's litigation over other monopoly abuse. The current Microsoft plan is to push the C# language, which is Microsoft's barely different copy of Java. But the core C# libraries will be only ever be available on Windows (there's an open source effort to duplicate some C# libraries on Linux, but few believe it will lead anywhere). The C# initiative will last only until Redmond wants to push the Next Incompatible Big Thing. Java is shaped by the computer industry as a whole, and will be around until industry reaches consensus that there is something better to replace Java.
Language and Libraries
Let's spend a minute to review some software terms that are often taken for granted. If you are already familiar with this, just skip ahead until you reach something new. The terminology is spelled out in detail here to give a solid basis for the material that follows in the rest of the book.
What a language is
When people talk about a "programming language", they mean things like: How the language describes data, The statements that work on data, and The ways the two can be put together. The set of rules describing how you can put together programs in the language is called a grammar. The grammar for a programming language is written in mathematical language, and it defines how expressions are formed, what statements look like, and so on. We'll stay away from mathematics and explain things in English. Java is a programming language in the same part of the languages family tree as C++, Pascal, or Basic. Java adopts ideas from non-mainstream languages like Smalltalk and Lisp, too. Java is a strongly typed language, meaning that the compiler strictly checks operations and will only allow those that are valid for that type of operand (you can't multiply two character strings, but you may append them) Java is object- tied to the statements that operate on the data. Object-oriented means more than just tying data to statements, and we expand on that in . Statements are grouped into what other languages call functions, procedures, or subroutines. In an object-oriented language, we call the functions methods as they are the method or way to process some data. Methods can call other methods and can be recursive (call themselves). Program execution begins in a method with the special name main(). Statements in Java look similar to statements in many other high-level languages. Here are some examples of Java statements:
y = y + 1; if ( isLeapYear(y) ) // this is a comment febDays = 29; else febDays = 28;
Although Java adds some new things, it is equally notable for what is left out. The designer of C++ once wrote, "Within C++, there is a much smaller and cleaner language struggling to get out," (Bjarne Stroustrup, The Design and Evolution of C++, Addison-Wesley, 1994: 207). Of the people who agree with that prophetic statement, many think that the name of that smaller and cleaner language is Java. Java has eight basic or primitive datatypes, such as integers, characters, and floating-point numbers. All data is represented as one of these eight built-in elementary types, or as an object or array made up of these types. The size of each type is laid down in the language and is the same on all platforms. Here are some other Java language features that will be covered in later chapters:
Threads. Threads let a single program do more than one
thing at once, just as timesharing lets a computer system run more than one program at once.
Exceptions. Exceptions help a programmer deal with error
conditions when most convenient, instead of cluttering up the main flow of control with lots of checking and error- handlingcode.
Garbage collection. With garbage collection, the run-time
library, not the programmer, manages the use of dynamic storage and reclaims (frees) memory that is no longer in use in a program.
A programming language typically has a specification, which is a weighty document saying what the expressions, statements, and their various groupings actually mean. That is, what changes in memory or control flow will occur when an expression is evaluated or a statement is executed. This is termed the semantics of the language. The first half of this book, up to
(semantics) of the Java language. Don't worrythe chapters are short and well organized. Sun has published a Java Language Specification (JLS). It is written mostly for an audience of compiler implementors, and is not intended as a tutorial for programmers (that's what this book is for). But it can be fun to dip into the JLS anyway when you want to play language lawyer or resolve a tricky question, and you can find it online at
What a library is
Early in the history of programming, people realized that some routines were needed over and over again in different programs. It makes sense to move frequently reused code into a separate file or library that all programs can share. The kind of code that belongs in a library are things like code to open a file, or read in a block of bytes, or get the current timestamp from the operating system. A library is not an executable program in its own right. It contains executable code that is brought into your program's address space, when your program calls a routine in the library. The work of finding the right library and loading its code into your process memory at run-time is called dynamic linking and it's an important feature of Java. "Dynamic" in compiler terminology just means "is done at run-time", and contrasts with "static" meaning "done at compile time". The entire set of routines in a library (the routine names, what they can return, and the parameter types) is known as the Application Programming Interface, or API. Modern languages check that the calls to a library are consistent with the API of the library implementation. The checking needs to be done twice: at compile time to catch any mismatches as early as possible, and at run-time to confirm that nothing has changed. So the compiler and the run-time environment both need to know where to find the application libraries.
Application Programmer Interface (API)
This is the set of libraries the programmer sees and uses when writing source code. An API consists of the names of the routines in a library, return types, and the number and types of parameters. For example, the POSIX 1003.1 Operating System standard says that every system complying with the standard will have a function with the following name and argument. It will return nonzero if ch is in the range of the 7-bit ASCII codes: int isascii(int ch); A program that uses only the routines specified in an API is compatible at the source code level with any OS that implements the API. Standard APIs make life easier for software vendors. Java has the same unified API on all computers. This was the part that Microsoft tried to break.
When working on large suites of programs, application programmers will frequently design and implement their own libraries (accumulation of re-usable routines). A retail sales application might have a library for a customer transaction, with all the operations you can do on a transaction: sale, return, void, or cancel. Any time a programmer wants code to process a transaction, he or she calls the appropriate library routine. If a bug is found in transaction code, it only needs to be fixed in one place (the library) and not in all the places where the library routine is called.
What the run-time library is
Just as application suites are supported by libraries, the compiler vendor provides a set of libraries collectively known as the run-time library. The run-time library or "the run-time" supports operations needed by programs in the course of execution. The classic run-time library handles a small number of house- keeping tasks like memory management, maintaining a stack, and dynamic array support. Programmers don't call routines in a classic run-time library; the calls are planted automatically by the compiler when needed. Apart from the implicit calls, there is no significant difference between code in the run-time library and code in an application library. It's implemented the same way and has the same overall goals. Programmers can count on the presence of the run-time library, but because they don't have to tell the compiler where to find it and because they don't call it explicitly, they sometimes aren't really aware of its presence.
Java takes a radically different approach. Java has a very extensive run-time librarygreater than any other programming language to date. In addition to the standard house-keeping operations in support of program execution, Java comes bundled with scores of packages (the Java term for a library) to carry out tasks useful to many applications. These libraries form part of the Java run-time library by definition, and you can absolutely depend on their standard presence in an implementation. Unlike a classic run-time library, the programmer will explicitly call routines in these Java packages when needed, and hence needs to know about the Java run- times and what they do.
Much of the value of Java is in this set of cross-platform APIs that come with the compiler system. Java has possibly the language. For example, there is a single library function to read a JPEG file and display it as an icon in a GUI. There is another library function to make a standard connection, known as a socket, to any program (not just Java code) on another computer anywhere on the Internet. Java makes network software easy to build.
Some of the standard Java packages are shown in
Table 1-1. A few of the many Java libraries (packages) available to all programs Package name Purpose java.lang This provides the core support for language features,
corresponding to a classic run-time library.
java.io This package provides basic I/O to the file system java.net This library contains the code that lets you implement network applications. java.util This library contains data structures (e.g. a tree, a set, a map) and common operations on them. Also other miscellaneous utility classes (date/time support, random numbers, etc.). java.util.regex Nested in the java.util package, this library supports text searching using regular expressions patterns. java.sql This library provides tools for database access.You can deduce that there is a hierarchy to package names: nested packages are shown by names separated by a period. E.g. there is a package called java.util full of utilities. One of its members is a package called java.util.regex, which has classes dealing with utilities for regular expressions. The hierarchy helps organize the hundreds of libraries, grouping related ones together. The package names shown in this table are exactly the names used in Java programs. Once a language has been specified and implemented, it is quite a big deal to make further changes to the language. However, it is trivial to add new libraries because they don't affect any existing programs, they don't need compiler or interpreter changes, and they don't change any tools that process object code. Each new release of Java has added some pretty hefty new packages. The has a table showing how Java has evolved over a series of successive releases. Up until Java 1.5, there had only been a few new features added to the language. Java 1.5 introduces a major new language feature called "generics" which is explained in
language and libraries is a witness to the increasing use of Java in new problem domains and applications.
One Size Doesn't Fit All
It's quite an accomplishment to run the same binary executable on such widely different architectures as MacOS, Windows, Linux and a quarter of a billion cell phones. There's more information about this coming up in
let's make an over-simplification and say that Java binary executables are interpreted on each platform. The Java binary format doesn't contain machine code instructions for any one computer. It contains a slightly higher level, more general, set of instructions known as byte code. To run a Java program, you actually run an interpreter. The interpreter reads the binary file containing the byte code and translates it into the machine code for the system where you are executing the program. The full and more complete story is in
card to a supercomputer cluster. That encompasses a wide range of hardware capabilitiesvirtual memory, hard disk, processor speed, file space, GUI abilities, memory size, and so on. Sun has achieved Java support on virtually every computing by defining different "editions." The smaller editions have a subset of the libraries in the bigger editions. JavaOne conference. See [1] I have a signet ring that runs Java programs! These rings were given out at the 1998
There are three editions of Java, and the smallest one is further sub-divided. For the sake of clarity, they should just have been called the small, medium and large editions, but the Java marketing folks at Sun gave them these names instead:
Micro Edition (the "small" platform)
The Micro Edition is a very low-footprint Java run-time environment, intended for embedding in consumer products like cell phones and other wireless devices, palmtops, or car navigation systems. You will develop your code using J2SE, and then deploy onto the various small devices. The Micro Edition is also known as Java 2 Micro Edition or "J2ME" for short.
The J2ME environment is further subdivided into "profiles." There is a profile (Connected Limited Device Configuration, or CLDC) that defines the libraries available for PDA-type hardware. I have a handheld Sharp Zaurus PDA which runs the Linux operating system just like one of my desktop systems, so PDAs can be pretty capable these days. Another profile (the Mobile Information Device Platform, MIDP) is for wireless devices such as cell phones. Cell phones today are general purpose computers, with a few special peripherals. The smallest profile, which runs in just 128 Kbytes of memory, is intended for smart cards. It's called the Java Card API. The guy at Sun in charge of really dumb names (like J2SE SDK, CLDC and MIDP) must have been on vacation the week the API for Java cards got named "the Java Card API". This profile is allowed to omit support for floating-point arithmetic when the hardware doesn't have it.
The J2ME environment is enjoying enormous success and has shipped in many millions of cell phones already. The year 2002 marked the point at which the number of handheld computing devices sold exceeded the number of PCs sold, so Java's success in this sector has real momentum. The Zelos Group (a company of technology analysts) predicts that Java will run on 450 million handsets by 2007, which is 75% of those shipping that year. As cell phone and PDA makers continue to search for the elusive sweet spot that combines the two products, Java dominates software for one, providing a bridge to the other. One programmer commented "by learning to program in Java, you free yourself from the limits of programming for just one OS or hardware product. It is an amazing feeling to see my apps running on my Palm Vx and my Motorola i95cl color Javaphone, and to know that they run just as well in any Nokia or Samsung or other java-enabled phone, on a RIM Blackberry, and on Windows CE." In May 2004, the top cable tv operators and suppliers (CableLabs, Charter, Cox, GoldPocket, Liberate, Motorola, Philips, Sun Microsystems, Time Warner Cable, and Vidiom Systems) jointly announced an initiative to develop a Java digital television API open standard. It is a CDLC profile called OnRamp, intended for legacy, resource-constrained cable television set-top boxes. It will be available to all set-top box vendors and digital tv developers, saving time and money for the entire industry.
Standard Edition (the "medium" platform)
Most people will work with this edition, as it is the edition with the libraries for desktop systems. The Standard Edition is also known as Java 2 Platform, Standard Edition or "J2SE" for short. Old-timers also use the abbreviation JDK (Java Development Kit) which was the term in use before Marketing and Legal rebadged it all. Using J2SE, you can write, deploy, and run Java programs for desktops and low-end servers. This text focuses on J2SE, which is the best edition for those learning Java. Java's compatibility ensures that everything you learn for J2SE also applies to programming the very large and the very small platforms. You can be a cell phone programmer, and a cable tv set-top box programmer, too. NASA's Mars Rover mission, which enjoyed great success in 2004, made extensive use of J2SE to control the vehicle and visually interpret the images sent back to earth.
Sun intends to ship new J2SE releases on a regular 12-18 month cycle, with each update combining improvements in quality and performance as well as a small number of new features. That's the intent, but some releases (like JDK 1.5) have a lot of new features and came out on an attenuated timeline (translation: there was so much new stuff, the schedule slipped).
Enterprise Edition (the "large" platform)
This development product is intended for those building enterprise-class server-based applications. It contains everything in the standard edition, and additional libraries for enterprise directories, transaction management, and enterprise messaging. The Enterprise Edition is also known as Java 2 Enterprise Edition or "J2EE" for short. This book describes several of the most popular libraries from the enterprise edition, including Java support for XML, for database access, and for servlets.
Book website/author email
In spite of everyone's efforts, all technical books contain at least one error. If you
find an error in this text, please let me know by email.My email address is at the end of the errata sheet for this book at
Some Light ReliefA Java Desktop Application
Do you have trouble keeping track of your disk usage? Do you sometimes need to free up space, but have no idea what to start deleting? Have a look at jDiskReport, which is a Java application written by expert programmer Karsten Lentzsch of Kiel in Germany. jDiskReport is a free cross-platform graphical disk report utility. It lets you understand how much space the files and directories consume on your hard disks.
shows jDiskReport but really doesn't do justice to the
program.
Figure 1-2. The jDiskReport: keeping track of
hard disk space.
[View full size image]
The jDiskReport software is freely from Karsten's website at
Download it and unzip the file. There is a
readme.txt and a jar file. Go to the directory containing those files, and start the program with the command line
java -jar jdiskreport.jar
The application will summarize the disk usage on your system and display it in a large variety of formats: oldest, largest, by type of file, pie chart, bar graph, text, tree display. This software was written once, and it runs on Linux, the Mac, Solaris, an HP Risc system, and so on. It is a very user friendly program, fast, and a good advert for the Java GUI library known as "Swing." Karsten has additional Java software on his website, too. If someone tells you that Java is only good for server software, show them this desktop application. Try it yourself; you'll probably find it very useful. the steps in to download a Java compiler. Then you can type in source code and test examples as we go along. The chapter presents some basics of Object Oriented Programming (OOP). We'll explain exactly what language designers mean by a type, and relate that to the objects in
OOP. We'll develop a type called Timestamp, then add a couple
of other types to turn it into a complete program. Along the way, we'll clarify the super-important distinction between "an object" and "a reference to an object". The chapter ends with the development of a small but complete running Java program that displays a desktop clock.
Downloading and Compiling Java
If you use Solaris or an Apple computer running MacOS X, a Java compiler is already installed on your system. So you folks can skip right ahead to "Running a Java Program". Dell and H-P preload Java libraries on their Windows PCs, but you still need to download a compiler. If you are using Windows, Linux, or Solaris, Sun's website at is the easiest place to get a free Java compiler. There are other places too. IBM has some great Java compiler and tool downloads. If you are using something other than Linux, MacOS, Windows or Solaris, find the Java compiler by searching the manufacturer's website.
Downloading a Java compiler system
Follow the steps in to download and install a Java Development Kit (JDK). The current version of the JDK is called "J2SE 1.5 SDK" i.e. Java 2 Standard Edition, version 1.5 of the Software Development Kit. Most people call it by the old, simpler name "JDK 1.5". If there is a newer version than 1.5, such as 1.5.1 or 1.6, get that instead.
Compiling a Java program
A lot of programmers use IDEs to develop their code, and there are many IDEs that support Java, including some free ones such as Sun's NetBeans, Eclipse, or the BlueJ environment. You can get a list by googling for "Java IDE". We'll avoid IDEs here and do everything from the command line, to keep the learning experience focused on Java. Create a separate work directory just for your files, and don't put your directory anywhere under the JDK installation directory. mkdir c:\work cd c:\work
After installing, you can run the Java compiler. Type this at the command shell:
javac
Assuming you installed the JDK and set the path correctly, you will get back a dozen lines of messages, starting with this line:
Usage: javac <options> <source files>
Voila, your first Java program (no file at all, which is even easier than "hello world") compiles OK. If you saw something different, like "javac not recognized", troubleshoot your installation and/or the path variable as outlined in .
Running a Java program
The next step is to run a Java program. Java was originally implemented as an interpreted language. You ran the interpreter program, the interpreter read the bytecode, and interpreted it into the corresponding instructions for that architecture. And that's still mostly true today for most implementations of Java. Sun refers to the interpreter program as the Java Virtual
Machine (JVM). The JVM, the run-time library, and the extensive
Java libraries together are known as the Java Runtime
Environment (JRE). The JRE does for Java applications roughly
what Microsoft's Common Language Runtime (CLR) does for .net applications. The CLR lets a program be written in any of several Windows languages and only run on Windows. The JRE lets a program (in any language that compiles to Java bytecode) run on every computer system.
That truly means Java runs on just about every computer system. Cell phones and digital cameras today contain general- purpose microprocessors, which is the main reason there's a few seconds ofdelay after turning them onthey take time to boot up. I haven't written a Java program for my digital camera yet, but there are plenty for my cell phone.
Interpreter performance boosts
A classic interpreter has a start-up performance issue: instead of the operating system loading your program into memory and executing it, the operating
system has to load the interpreter program into memory and execute it, followed
by the interpreter program loading the run-time library and your program into memory and executing that. So interpreted programs have twice the start-up overhead of programs that have been compiled to native code. This doesn't matter for server code, but has dampened Java's popularity for desktop applications.Class data sharing
A huge amount of effort has been devoted to speeding up Java
and the JVM interpreter. JDK 1.5 brings in a new and significant optimization called class data sharing. Thistechnique maps most of the run-time library into the JVM as a
memory image, rather than loading it from a series of class files. Although memory mapped I/O is fast (seedetails), it makes the process look bigger to some Windows tools (wrongly) than if you had loaded the same content through the link-loader.
Footprint reduction Also in JDK 1.5, as much as possible of the run-time library
(several MB) is now shared among JVM instances, rather than
loaded into each individually. This will improve performancewhen you run several Java programs at once. Everyone hopes
that class data sharing will give great results, rejuvenating Java on the desktop.Hotspot Sun's JVM uses a technique called Just In Time compiling (JIT) to complete
compilation at run-time, translating from byte code to native machine code. Sun calls its JIT implementation the "Hotspot"TM compiler. There's a trade-off between the time the JVM spends optimizing the translation, and the time you save because your code now runs faster. The JVM tries to reduce the work by only translating the tight loops or "hot spots" of code, not the whole program. Most benchmarks show that Java code runs as fast as optimized native code, once the program starts. Continuing the discussion of setting up Java, here's the command that runs a Java program:
java classname
We are going to use a digital clock program as an example in the rest of the chapter. You can download the clock.java source code file from or you can type in the code from the listings later in the chapter. Either way, make sure the files are in your work directory and "cd" to it, so it becomes your current working directory. After successfully compiling, you can run a program with the main code in a class called "clock" by typing:
java clock
When you compile and run the example program, a window containing a digital clock display appears, and the display keeps updated with the current time. The commands to compile and run are shown in . The example uses a Mac.
Figure 2-1. Compiling and running clock.java
The javac command will create a file called "clock.class" containing the bytecode. If you create the same files on a windows system (or move the clock.class file from any system over to a windows system), you can execute it with the command "java clock". You will see a window like appear, and keep time:
Figure 2-2. Running the same clock program on Windows
Download or type in, then compile and run clock.java now. Don't sweat the details about understanding individual lines of code; we will go over them in the following sections. It's time to say a few words about classes and objects.