1. Trang chủ
  2. » Công Nghệ Thông Tin

Prentice hall just java 2 6th edition jul 2004 ISBN 0131482114

1,9K 145 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 1.869
Dung lượng 9,49 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The first edition of Just Java was one of the earliest books to accompany the original release of Java in 1996.. Behind all this, Java ismore than just the latest, most popular programmi

Trang 1

programming techniques Just Java(TM) 2,

Trang 2

latest Tomcat and servlet specifications.

Extensive new coverage includes:

New chapters on generics and enumerated types

Peter van der Linden delivers expert advice, clear explanations, and crisp sample

Trang 3

matching, network software, mapped I/O, utilities and generic collections

Trang 13

by the United States Government is subject to the restrictionsset 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 inthis 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,

U.S., please contact International Sales, 1-317-581-3793, international@pearsontechgroup.com

Trang 14

computer industry all my life, and in the last few years started teaching 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 my

students past and present, and all my teachers, young and old.

Trang 15

The first edition of Just Java was one of the earliest books to

accompany the original release of Java in 1996 The launch ofJava coincided with the explosion of interest in the web and thenet 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 rapidlycreate new hardware and software products; everyone wrotesoftware to display stock prices on their desktops and cell

Trang 16

Library changes:

Delegation based event-handlers

Chapter 20

I/O Readers and Writers

Chapter 21

Collection classes, JDBC enhancements

Chapter 16 , 23 - 24

Thread local storage Chapter 14

Java 2 v1.3 May 2000 Performance and bug

fixes, no significant changes

Chapter 18

Trang 17

backward compatibility and portability The Java 1.2 release was

a significant one, bundling major functionality improvementslike the collection classes and the Swing GUI library Java 1.3and 1.4 were comparatively smaller, although 1.4 did bring anew 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 Sunwill probably rename Java 1.5 to some awkward and confusingname using two sets of numbers, like "Java 2 Mega-edition v1.5fab-o-lux" Whatever they call it, think of Java 1.5 as "Java 3"

Trang 18

printf (like C's printf) Chapter 17

java.util.scanner (fourth attempt at fixing I/O)

Chapter 17

java.util.concurrent thread utilities

Chapter 14

javax.xml XML support bundled

Chapter 27 , 28

Class data sharing Chapter 2

Can add Swing components directly to a Container!

Chapter 21

There are also the traditional bug-fix, library and performanceimprovements, including some exciting optimizations for

desktop applications

Over the years, I've put a lot of hard work into unlocking thechanges 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 theinformation 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 myfriend Alan Abel suggested) in a more prominent position

P

Trang 19

I'm very grateful to the following people, who are some of themost talented and creative individuals you'll find:

Trang 20

groups

The editorial, marketing, and production teams at Prentice-Halland Sun Microsystems deserve full appreciation:

Greg Doench, Chris Guzikowski, Julie Nahil, Raquel Kaplan, NinaScuderi, 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?

Trang 21

Chapter 1 What Can Java Do for Me?

Chapter 2 Introducing Objects

Chapter 3 Primitive Types, Wrappers, and BoxingChapter 4 Statements and Comments

Chapter 5 OOP Part IIConstructors and VisibilityChapter 6 Static, Final, and Enumerated TypesChapter 7 Names, Operators, and Accuracy

Trang 22

compilers and source code are available for free download frommany different organizations Just about the entire computerindustry is backing Java enthusiastically with products and

support In this chapter we'll look at the reasons behind Java'spopularity, and summarize the key features of the language

Java works well for web and server-based applications It hasgreat features like object-oriented programming, easy databaseaccess, and well-designed GUI support The latest release, Java

2 version 1.5, has performance tweaks to speed up desktopprograms 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 ismore than just the latest, most popular programming language

It is a way of creating applications that are independent of allhardware and all operating systems

Trang 23

What is meant by "applications that are independent of all

hardware and operating systems?" It means you can compile aJava 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 thevarieties of Unix, on IBM's mainframe operating systems, on cellphones, Personal Digital Assistants (PDAs), embedded

processors, and even on smart cards (credit cards with a

microprocessor and memory), as shown in Figure 1-1

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]

Trang 24

releases, like Microsoft's Longhorn Java will be ported to allfuture operating systems of significance It's also a fast way fornew hardware to get software applications that will run on it

Java unlocks software from being coupled to any specific OSand hardware platform This new flexibility has made Java verypopular with users, IT departments, and software vendors Allthree benefit enormously from software portability

Trang 25

You might think that software portability does not affect you:your application software runs fine on your PC today and that'sall you use And that's true, right up until the time you want toconsider a new or different system

Say you're in the market to buy a new desktop system, and afriend shows you the video-editing, music, virus resistance, anddigital picture capabilities of his Apple Macintosh You considerswitching to a Mac Switching GUIs is a no-brainerGUIs all doessentially the same things, and it only takes a day or two tore-train your fingers The problem is the apps You are facedwith the "choice" of walking away from your investment in yourexisting PC-only software, or buying yet another Windows PCthat has some compatibility with your previous system You caneasily switch hardware from Dell to H-P or IBM, but there's asoftware barrier to switching from Windows to something withfewer security problems, like Linux or MacOS You've been

locked in

When your application programs are written in Java, you canupgrade OS and applications independently You can try Linuxand still use your familiar applications You can move your

existing Java programs to any new system, and carry on usingthem 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 overjust 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, andLonghorn on the horizon These platforms have subtle and

different incompatibilities amongthem Even applications

running on a single platform have limited interoperability Older

Trang 26

default from the latest Microsoft Office, even when the filesdon'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 offfrom reading new files)

Software portability is all about "future-proofing" your softwareinvestment Rewrite it in Java, and that's the last port you'llever need to do Portability is the Holy Grail of the softwareindustry It has long been sought, but never before attained.Java brings the industry closer to true software portability thanany previous system has

Trang 27

http://www.openoffice.org/dev_docs/source/sdk/

Java and jobs

Software portability has a wonderful side-effect: skills

sourcing programming jobs to countries with low direct laborcosts It's a short-term cost-saving that looks good on paper,until you look at the wider implications

portability for programmers Many companies today are out-The beneficiaries of jobs exported from the West are Asian

countries with poor performance in the annual global survey ofcorruption (see www.transparency.org) It's a risky long-termbet to move strategic expertise to countries that combine

Trang 28

intellectual property laws, with scant free market experience,and no effective environmental or workplace regulation Thebigger picture needs to be thought through when choosing toexport jobs and assets from our home economies As peoplewith a stake in the computer industry, we have a duty to makeour views (whatever they are) known to politicians

Looking at this another way, China (a nation of 1.3 billion) hasalready standardized on Linux, and India (1 billion people) isreviewing it Java offers the only viable way to create softwaretargeted 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 OSexperience ("must have 2 years of MVS on OS/390") and ignoreother 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 ofthe US's largest job sites reflected these hiring needs

Microsoft's C# was mentioned in about 1400 postings, whileC++ was a requirement in about 4000 postings That's whatyou would expect C++ is much more widespread than C#, andruns on many more computers But Java was a surprise: morethan 6800 postings sought Java skills More employers wantedJava 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 another11% plan to start in the next year Investing some of your time

in Java is good for your career

Java and Microsoft

Trang 29

Software that can run on any operating system has a largermarket than software that is limited to Windows only Over timeISVs 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 Javaproduct 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 isMicrosoft's barely different copy of Java But the core C#

libraries will be only ever be available on Windows (there's anopen source effort to duplicate some C# libraries on Linux, butfew believe it will lead anywhere) The C# initiative will last onlyuntil Redmond wants to push the Next Incompatible Big Thing.Java is shaped by the computer industry as a whole, and will bearound until industry reaches consensus that there is somethingbetter to replace Java

Trang 30

Let's spend a minute to review some software terms that areoften 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 materialthat follows in the rest of the book

What a language is

When people talk about a "programming language", they meanthings like:

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 adoptsideas 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 thatare valid for that type of operand (you can't multiply two

oriented, meaning that the data declarations are very closely

Trang 31

on that in chapters 2 and 5

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 methodsand can be recursive (call themselves) Program execution

begins in a method with the special name main().Statements

out," (Bjarne Stroustrup, The Design and Evolution of C++,

Addison-Wesley, 1994: 207) Of the people who agree with thatprophetic statement, many think that the name of that smaller

Trang 32

thing at once, just as timesharing lets a computer systemrun more than one program at once

Exceptions Exceptions help a programmer deal with error

conditions when most convenient, instead of cluttering upthe 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 dynamicstorage and reclaims (frees) memory that is no longer inuse 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

Sun has published a Java Language Specification (JLS) It iswritten mostly for an audience of compiler implementors, and is

Trang 33

What a library is

Early in the history of programming, people realized that someroutines 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 afile, or read in a block of bytes, or get the current timestampfrom the operating system

A library is not an executable program in its own right It

contains executable code that is brought into your program'saddress 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 contrastswith "static" meaning "done at compile time"

The entire set of routines in a library (the routine names, whatthey can return, and the parameter types) is known as the

Application Programming Interface, or API Modern languagescheck that the calls to a library are consistent with the API ofthe library implementation The checking needs to be done

twice: at compile time to catch any mismatches as early aspossible, and at run-time to confirm that nothing has changed

So the compiler and the run-time environment both need toknow where to find the application libraries

Trang 34

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 inone place (the library) and not in all the places where the

library routine is called

Trang 35

no significant difference between code in the run-time libraryand code in an application library It's implemented the sameway and has the same overall goals Programmers can count onthe presence of the run-time library, but because they don'thave to tell the compiler where to find it and because they don'tcall 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 programminglanguage to date In addition to the standard house-keepingoperations 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 formpart 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 packageswhen 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 APIsthat come with the compiler system Java has possibly the

easiest-to-use networking and windowing (GUI) support of any

Trang 36

a JPEG file and display it as an icon in a GUI There is anotherlibrary function to make a standard connection, known as asocket, to any program (not just Java code) on another

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 itsmembers is a package called java.util.regex, which has classesdealing with utilities for regular expressions The hierarchy

Trang 37

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'taffect 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 somepretty hefty new packages

The Preface on page xix 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 Chapter 15 Growth in the

language and libraries is a witness to the increasing use of Java

in new problem domains and applications

Trang 38

It's also not easy to run software on everything from a smartcard 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 computingdevice[1] by defining different "editions." The smaller editionshave a subset of the libraries in the bigger editions

[1] I have a signet ring that runs Java programs! These rings were given out at the 1998

JavaOne conference See www.ibutton.com

There are three editions of Java, and the smallest one is furthersub-divided For the sake of clarity, they should just have beencalled the small, medium and large editions, but the Java

marketing folks at Sun gave them these names instead:

Micro Edition (the "small" platform)

Trang 39

environment, intended for embedding in consumer products likecell phones and other wireless devices, palmtops, or car

navigation systems You will develop your code using J2SE, andthen deploy onto the various small devices The Micro Edition isalso 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, orCLDC) that defines the libraries available for PDA-type

hardware I have a handheld Sharp Zaurus PDA which runs theLinux operating system just like one of my desktop systems, soPDAs can be pretty capable these days Another profile (theMobile 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 smallestprofile, which runs in just 128 Kbytes of memory, is intendedfor smart cards It's called the Java Card API The guy at Sun incharge of really dumb names (like J2SE SDK, CLDC and MIDP)must have been on vacation the week the API for Java cards gotnamed "the Java Card API" This profile is allowed to omit

support for floating-point arithmetic when the hardware doesn'thave it

The J2ME environment is enjoying enormous success and hasshipped in many millions of cell phones already The year 2002marked the point at which the number of handheld computingdevices sold exceeded the number of PCs sold, so Java's

success in this sector has real momentum The Zelos Group (acompany of technology analysts) predicts that Java will run on

450 million handsets by 2007, which is 75% of those shippingthat year As cell phone and PDA makers continue to search forthe elusive sweet spot that combines the two products, Javadominates 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

Trang 40

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."

television set-top boxes It will be available to all set-top boxvendors and digital tv developers, saving time and money forthe entire industry

Standard Edition (the "medium" platform)

Most people will work with this edition, as it is the edition withthe libraries for desktop systems The Standard Edition is alsoknown as Java 2 Platform, Standard Edition or "J2SE" for short.Old-timers also use the abbreviation JDK (Java DevelopmentKit) which was the term in use before Marketing and Legal

rebadged it all Using J2SE, you can write, deploy, and run Javaprograms for desktops and low-end servers

This text focuses on J2SE, which is the best edition for thoselearning Java Java's compatibility ensures that everything youlearn for J2SE also applies to programming the very large andthe very small platforms You can be a cell phone programmer,and a cable tv set-top box programmer, too NASA's Mars Rovermission, which enjoyed great success in 2004, made extensiveuse 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

Ngày đăng: 26/03/2019, 16:10