Termes les plus recherchés
[PDF](+50👁️) Télécharger Go Freebooks.com Java En ( 7) pdf
go-freebooks.com-java-en (7)Télécharger gratuit Go Freebooks.com Java En ( 7) pdf
TM
Updated and
Expanded for
A Beginner's Guide
Third Edition
1
BONUS!
hWrt.osbrjrne-.Hjni
Herbert Schildt
The WfO Md'5. *l programming aulhor with
more than 3 million books scrHtaM LiriG
TM
Java :
A Beginner's Guide,
Third Edition
TERM LlflG
This page intentionally left blank.
TERM LlflG
TM
Java :
A Beginner's Guide,
Third Edition
Herbert Schildt
McGraw-Hill/Osborne
New York Chicago San Francisco
Lisbon London Madrid Mexico City
Milan New Delhi San Juan
Seoul Singapore Sydney Toronto
TERM LlflG
The McGwwHiil Companies
Copyright © 2005 by The McGraw-Hill Companies. All rights reserved. Manufactured in the United
States of America. Except as permitted under the United States Copyright Act of 976, no part of
this publication may be reproduced or distributed in any form or by any means, or stored in a
database or retrieval system, without the prior written permission of the publisher.
0-07-146650-9
The material in this eBook also appears in the print version of this title: 0-07-2231890-0.
All trademarks are trademarks of their respective owners. Rather than put a trademark symbol after
every occurrence of a trademarked name, we use names in an editorial fashion only, and to the
benefit of the trademark owner, with no intention of infringement of the trademark. Where such
designations appear in this book, they have been printed with initial caps. McGraw-Hill eBooks are
available at special quantity discounts to use as premiums and sales promotions, or for use in
corporate training programs. For more information, please contact George Hoare, Special Sales, at
george_hoare@mcgraw-hill.com or (212) 904-4069.
TERMS OF USE
This is a copyrighted work and The McGraw-Hill Companies, Inc. ("McGraw-Hill") and its
licensors reserve all rights in and to the work. Use of this work is subject to these terms. Except as
permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the work,
you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works
based upon, transmit, distribute, disseminate, sell, publish or sublicense the work or any part of it
without McGraw-Hill's prior consent. You may use the work for your own noncommercial and
personal use; any other use of the work is strictly prohibited. Your right to use the work may be
terminated if you fail to comply with these terms.
THE WORK IS PROVIDED "AS IS." McGRAW-HILL AND ITS LICENSORS MAKE NO
GUARANTEES OR WARRANTIES AS TO THE ACCURACY, ADEQUACY OR
COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK,
INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA
HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. McGraw-Hill and its
licensors do not warrant or guarantee that the functions contained in the work will meet your
requirements or that its operation will be uninterrupted or error free. Neither McGraw-Hill nor its
licensors shall be liable to you or anyone else for any inaccuracy, error or omission, regardless of
cause, in the work or for any damages resulting therefrom. McGraw-Hill has no responsibility for
the content of any information accessed through the work. Under no circumstances shall McGraw-
Hill and/or its licensors be liable for any indirect, incidental, special, punitive, consequential or
similar damages that result from the use of or inability to use the work, even if any of them has been
advised of the possibility of such damages. This limitation of liability shall apply to any claim or
cause whatsoever whether such claim or cause arises in contract, tort or otherwise.
DOI: 10.1036/0071466509
TERM LlflG
3 Professional
Want to learn more?
We hope you enjoy this
McGraw-Hill eBook! If
you'd like more information about this book,
its author, or related books and websites,
please click here.
About the Author
Herbert Schildt is the world's leading programming author.
He is an authority on the C, C++, Java, and C# languages,
and he is a master Windows programmer. His programming
books have sold more than 3 million copies worldwide and
have been translated into all major languages. He is the author
of numerous bestsellers, including Java: The Complete
Reference, C++: The Complete Reference, C: The Complete
Reference, and C#: The Complete Reference, and he is the
co-author of The Art of Java. Schildt holds both graduate and
undergraduate degrees from the University of Illinois. He can
be reached at his consulting office at (217) 586-4683. His Web
site is www.HerbSchildt.com.
Copyright © 2005 The McGraw-Hill Companies. Click here for terms of use.
TERM LlflG
Contents at a Glance
1 Java Fundamentals 1
2 Introducing Data Types and Operators 35
3 Program Control Statements 71
4 Introducing Classes, Objects, and Methods 115
5 More Data Types and Operators 151
6 A Closer Look at Methods and Classes 201
7 Inheritance 251
8 Packages and Interfaces 301
9 Exception Handling 333
10 Using I/O 365
1 1 Multithreaded Programming 407
1 2 Enumerations, Autoboxing, and Static Import 447
13 Generics 481
14 Applets, Events, and Miscellaneous Topics 525
VII
TERM LlflG
viii Java: A Beginner's Guide
A Answers to Mastery Checks 557
B Using Java's Documentation Comments 603
Index 613
TERM LlflG
For more information about this title, click here
Contents
PREFACE xix
1 Java Fundamentals 1
The Origins of Java 2
How Java Relates to C and C++ 3
How Java Relates to C# 4
Java's Contribution to the Internet 5
Java Applets 5
Security 5
Portability 6
Java's Magic: The Bytecode 6
The Java Buzzwords 7
Object-Oriented Programming 8
Encapsulation 9
Polymorphism 10
Inheritance 10
Obtaining the Java Development Kit 12
A First Simple Program 12
Entering the Program 13
Compiling the Program 13
The First Sample Program Line by Line 14
ix
term Line
X Java: A Beginner's Guide
Handling Syntax Errors 17
A Second Simple Program 17
Another Data Type 20
Project 1-1 Converting Gallons to Liters 22
Two Control Statements 23
The if Statement 23
The for Loop 25
Create Blocks of Code 27
Semicolons and Positioning 29
Indentation Practices 29
Project 1-2 Improving the Gallons-to-Liters Converter 30
The Java Keywords 32
Identifiers in Java 32
The Java Class Libraries 33
Module 1 Mastery Check 34
2 Introducing Data Types and Operators 35
Why Data Types Are Important 36
Java's Primitive Types 36
Integers 37
Floating-Point Types 38
Characters 40
The Boolean Type 41
Project 2-1 How Far Away Is the Lightning? 43
Literals 44
Hexadecimal and Octal Constants 44
Character Escape Sequences 45
String Literals 45
A Closer Look at Variables 47
Initializing a Variable 47
Dynamic Initialization 48
The Scope and Lifetime of Variables 49
Operators 52
Arithmetic Operators 52
Increment and Decrement 54
Relational and Logical Operators 55
Short-Circuit Logical Operators 57
The Assignment Operator 58
Shorthand Assignments 60
Type Conversion in Assignments 61
Casting Incompatible Types 62
Operator Precedence 64
Project 2-2 Display a Truth Table for the Logical Operators 65
TERM LlflG
Contents
Expressions 66
Type Conversion in Expressions 66
Spacing and Parentheses 68
Module 2 Mastery Check 69
3 Program Control Statements 71
Input Characters from the Keyboard 72
The if Statement 74
Nested ifs 75
The if-else-if Ladder 76
The switch Statement 78
Nested switch Statements 82
Project 3-1 Start Building a Java Help System 83
The for Loop 86
Some Variations on the for Loop 87
Missing Pieces 88
Loops with No Body 90
Declaring Loop Control Variables Inside the for Loop 91
The Enhanced for Loop 92
The while Loop 92
The do-while Loop 94
Project 3-2 Improve the Java Help System 97
Use break to Exit a Loop 100
Use break as a Form of goto 102
Use continue 106
Project 3-3 Finish the Java Help System 109
Nested Loops 112
Module 3 Mastery Check 113
4 Introducing Classes, Objects, and Methods 115
Class Fundamentals 116
The General Form of a Class 116
Defining a Class 117
How Objects Are Created 121
Reference Variables and Assignment 121
Methods 122
Adding a Method to the Vehicle Class 123
Returning from a Method 125
Returning a Value 126
Using Parameters 129
Adding a Parameterized Method to Vehicle 130
Project 4-1 Creating a Help Class 133
Constructors 139
Parameterized Constructors 140
Adding a Constructor to the Vehicle Class 141
TERM LlflG
xii Java: A Beginner's Guide
The new Operator Revisited 142
Garbage Collection and Finalizers 143
The fmalize( ) Method 144
Project 4-2 Demonstrate Finalization 145
The this Keyword 147
Module 4 Mastery Check 149
5 More Data Types and Operators 151
Arrays 152
One-Dimensional Arrays 152
Project 5-1 Sorting an Array 156
Multidimensional Arrays 158
Two-Dimensional Arrays 158
Irregular Arrays 1 60
Arrays of Three or More Dimensions 161
Initializing Multidimensional Arrays 161
Alternative Array Declaration Syntax 163
Assigning Array References 164
Using the length Member 165
Project 5-2 A Queue Class 168
The For-Each Style for Loop 172
Iterating Over Multidimensional Arrays 175
Applying the Enhanced for 177
Strings 178
Constructing Strings 178
Operating on Strings 179
Arrays of Strings 181
Strings Are Immutable 182
Using Command-Line Arguments 183
The Bitwise Operators 185
The Bitwise AND, OR, XOR, and NOT Operators 186
The Shift Operators 191
Bitwise Shorthand Assignments 193
Project 5-3 A ShowBits Class 193
The? Operator 196
Module 5 Mastery Check 198
6 A Closer Look at Methods and Classes 201
Controlling Access to Class Members 202
Java's Access Specifiers 202
Project 6-1 Improving the Queue Class 208
Pass Objects to Methods 209
How Arguments Are Passed 211
Returning Objects 214
TERM LlflG
Contents xiii
Method Overloading 216
Overloading Constructors 222
Project 6-2 Overloading the Queue Constructor 225
Recursion 228
Understanding static 230
Static Blocks 233
Project 6-3 The Quicksort 235
Introducing Nested and Inner Classes 238
Varargs: Variable-Length Arguments 242
Varargs Basics 242
Overloading Varargs Methods 246
Varargs and Ambiguity 247
Module 6 Mastery Check 249
7 Inheritance 251
Inheritance Basics 252
Member Access and Inheritance 255
Constructors and Inheritance 258
Using super to Call Superclass Constructors 260
Using super to Access Superclass Members 266
Project 7-1 Extending the Vehicle Class 267
Creating a Multilevel Hierarchy 270
When Are Constructors Called? 273
Superclass References and Subclass Objects 274
Method Overriding 280
Overridden Methods Support Polymorphism 283
Why Overridden Methods? 285
Applying Method Overriding to TwoDShape 285
Using Abstract Classes 290
Using final 295
final Prevents Overriding 295
final Prevents Inheritance 295
Using final with Data Members 296
The Object Class 298
Module 7 Mastery Check 299
8 Packages and Interfaces 301
Packages 302
Defining a Package 302
Finding Packages and CLASSPATH 304
A Short Package Example 304
Packages and Member Access 306
A Package Access Example 307
Understanding Protected Members 309
Importing Packages 311
TERM LlflG
xiv Java: A Beginner's Guide
Java's Class Library Is Contained in Packages 314
Interfaces 315
Implementing Interfaces 316
Using Interface References 320
Project 8-1 Creating a Queue Interface 322
Variables in Interfaces 328
Interfaces Can Be Extended 329
Module 8 Mastery Check 330
9 Exception Handling 333
The Exception Hierarchy 334
Exception Handling Fundamentals 334
Using try and catch 335
A Simple Exception Example 336
The Consequences of an Uncaught Exception 339
Exceptions Enable You to Handle Errors Gracefully 340
Using Multiple catch Statements 342
Catching Subclass Exceptions 343
Try Blocks Can Be Nested 344
Throwing an Exception 346
Rethrowing an Exception 346
A Closer Look at Throwable 348
Using finally 350
Using throws 352
Java's Built-in Exceptions 354
Creating Exception Subclasses 356
Project 9-1 Adding Exceptions to the Queue Class 359
Module 9 Mastery Check 362
10 Using I/O 365
Java's I/O Is Built upon Streams 366
Byte Streams and Character Streams 366
The Byte Stream Classes 367
The Character Stream Classes 367
The Predefined Streams 367
Using the Byte Streams 370
Reading Console Input 370
Writing Console Output 372
Reading and Writing Files Using Byte Streams 373
Inputting from a File 374
Writing to a File 376
Reading and Writing Binary Data 378
Project 10-1 A File Comparison Utility 382
Random Access Files 384
TERM LlflG
Contents XV
Using Java's Character-Based Streams 387
Console Input Using Character Streams 388
Console Output Using Character Streams 391
File I/O Using Character Streams 393
Using a File Writer 393
Using a FileReader 394
Using Java's Type Wrappers to Convert Numeric Strings 396
Project 10-2 Creating a Disk-Based Help System 399
Module 10 Mastery Check 406
1 1 Multithreaded Programming 407
Multithreading Fundamentals 408
The Thread Class and Runnable Interface 409
Creating a Thread 410
Some Simple Improvements 413
Project 11-1 Extending Thread 415
Creating Multiple Threads 418
Determining When a Thread Ends 421
Thread Priorities 424
Synchronization 428
Using Synchronized Methods 428
The synchronized Statement 43 1
Thread Communication Using notify( ), wait( ), and notify All( ) 434
An Example That Uses wait( ) and notify( ) 435
Suspending, Resuming, and Stopping Threads 440
Project 11-2 Using the Main Thread 444
Module 1 1 Mastery Check 446
1 2 Enumerations, Autoboxing, and Static Import 447
Enumerations 448
Enumeration Fundamentals 449
Java Enumerations Are Class Types 452
The values( ) and valueOf( ) Methods 452
Constructors, Methods, Instance Variables, and Enumerations 454
Two Important Restrictions 456
Enumerations Inherit Enum 456
Project 12-1 A Computer-Controlled Traffic Light 458
Autoboxing 464
Type Wrappers 465
Autoboxing Fundamentals 467
Autoboxing and Methods 468
Autoboxing/Unboxing Occurs in Expressions 470
A Word of Warning 471
Static Import 472
TERM LlflG
xvi Java: A Beginner's Guide
Metadata 476
Module 12 Mastery Check 479
13 Generics 481
Generics Fundamentals 482
A Simple Generics Example 483
Generics Work Only with Objects 487
Generic Types Differ Based on Their Type Arguments 487
A Generic Class with Two Type Parameters 488
The General Form of a Generic Class 490
Bounded Types 490
Using Wildcard Arguments 494
Bounded Wildcards 498
Generic Methods 501
Generic Constructors 504
Generic Interfaces 505
Project 13-1 Create a Generic Queue 508
Raw Types and Legacy Code 513
Erasure 516
Ambiguity Errors 517
Some Generic Restrictions 519
Type Parameters Can't Be Instantiated 519
Restrictions on Static Members 520
Generic Array Restrictions 520
Generic Exception Restriction 522
Continuing Your Study of Generics 522
Module 13 Mastery Check 522
14 Applets, Events, and Miscellaneous Topics 525
Applet Basics 526
Applet Organization and Essential Elements 530
The Applet Architecture 530
A Complete Applet Skeleton 531
Applet Initialization and Termination 532
Requesting Repainting 533
The update( ) Method 534
Project 14-1 A Simple Banner Applet 535
Using the Status Window 539
Passing Parameters to Applets 540
The Applet Class 542
Event Handling 544
The Delegation Event Model 544
Events 544
Event Sources 545
TERM LlflG
Contents xvii
Event Listeners 545
Event Classes 545
Event Listener Interfaces 546
Using the Delegation Event Model 548
Handling Mouse Events 548
A Simple Mouse Event Applet 549
More Java Keywords 552
The transient and volatile Modifiers 552
instanceof 553
strictfp 553
assert 553
Native Methods 554
What Next? 555
Module 14 Mastery Check 556
A Answers to Mastery Checks 557
B Using Java's Documentation Comments 603
The javadoc Tags 604
@author 605
{@code} 605
©deprecated 605
{@docRoot} 606
©exception 606
{@inheritDoc} 606
{@link} 606
{@linkplain} 606
{©literal} 606
@param 607
@return 607
@see 607
@serial 607
@serialData 608
@serialField 608
@since 608
©throws 608
{@value} 608
@version 609
The General Form of a Documentation Comment 609
What javadoc Outputs 609
An Example that Uses Documentation Comments 610
Index 613
TERM LlflG
This page intentionally left blank.
TERM LlflG
Preface
Java is the preeminent language of the Internet. Moreover, it is the universal language of
Web programmers around the world. To be a professional Web developer today implies
proficiency in Java. Therefore, if Internet-based programming is in your future, you have
chosen the right language to learn — and, this book will help you learn it.
The purpose of this book is to teach you the fundamentals of Java programming. It uses a
step-by-step approach complete with numerous examples, self-tests, and projects. It assumes
no previous programming experience. The book starts with the basics, such as how to compile
and run a Java program. It then discusses every keyword in the Java language. It concludes
with some of Java's most advanced features, such as multithreaded programming, generics,
and applets. By the time you finish, you will have a firm grasp of the essentials of Java
programming.
It is important to state at the outset that this book is just a starting point. Java is more than
just the elements that define the language. Java also includes extensive libraries and tools that
aid in the development of programs. Furthermore, Java provides a sophisticated set of libraries
that handle the browser user interface. To be a top-notch Java programmer implies mastery of
these areas, too. After completing this book, you will have the knowledge to pursue any and
all other aspects of Java.
xix
Copyright © 2005 The McGraw-Hill Companies. Click here for terms of use.
TERM LlflG
XX Java: A Beginner's Guide
The Evolution of Java
Only a few languages have fundamentally reshaped the very essence of programming. In this
elite group, one stands out because its impact was both rapid and widespread. This language
is, of course, Java. It is not an overstatement to say that the original release of Java 1.0 in
1995 by Sun Microsystems caused a revolution in programming. This revolution radically
transformed the Web into a highly interactive environment. In the process, Java set a new
standard in computer language design.
Over the years, Java continued to grow, evolve, and otherwise redefine itself. Unlike many
other languages, which are slow to incorporate new features, Java has continually been at the
forefront of computer language design. One reason for this is the culture of innovation and
change that came to surround Java. As a result, Java has gone through several upgrades — some
relatively small, others more significant.
The first major update to Java was version 1.1. The features added by Java 1 . 1 were more
substantial than the small increase in the version number would have you think. For example,
Java 1 . 1 added many new library elements, redefined the way events are handled, and
reconfigured many features of the original 1.0 library.
The next major release of Java was Java 2, where the 2 indicates "second generation." The
creation of Java 2 was a watershed event, marking the beginning of Java's "modern age."
The first release of Java 2 carried the version number 1.2. It may seem odd that the first release
of Java 2 used the 1.2 version number. The number originally referred to the internal version
number of the Java libraries, but then was generalized to refer to the entire release, itself. With
Java 2, Sun repackaged the Java product as J2SE (Java 2 Platform Standard Edition), and the
version numbers began to be applied to that product.
The next upgrade of Java was J2SE 1.3. This version of Java was the first major upgrade
to the original Java 2 release. For the most part it added to existing functionality and
"tightened up" the development environment. The release of J2SE 1.4 further enhanced Java.
This release contained several important new features, including chained exceptions, channel-
based I/O, and the assert keyword.
The latest release of Java is J2SE 5. As important as each of the preceding upgrades to
Java have been, none compares in scale, size, and scope to that of J2SE 5. It has fundamentally
reshaped the Java world!
TERM LlflG
Preface xxi
J2SE 5: The Second Java Revolution
Java 2 Platform Standard Edition, version 5 (J2SE 5) marks the beginning of the second Java
revolution. J2SE 5 adds many new features to Java that fundamentally change the character of
the language, increasing both its power and its range. So profound are these additions that they
will forever alter the way that Java code is written. J2SE 5 is a revolutionary force that cannot
be ignored.
To give you an idea of the scope of the changes caused by J2SE 5, here is a list of its major
new features covered in this book:
•
Generics
•
Autoboxing/unboxing
•
Enumerations
•
The enhanced, "for-each" style for loop
•
Variable-length arguments (varargs)
•
Static import
•
Metadata (annotations)
This is not a list of minor tweaks or incremental upgrades. Each item in the list represents
a significant addition to the Java language. Some, such as generics, the enhanced for, and
varargs, introduce new syntax elements. Others, such as autoboxing and auto-unboxing, alter
the semantics of the language. Metadata adds an entirely new dimension to programming.
In all cases, substantial functionality has been added.
The importance of these new features is reflected in the use of the version number 5. The
next version number for Java would normally have been 1.5. However, the changes and new
features are so significant that a shift from 1.4 to 1.5 just didn't seem to express the magnitude
of the change. Instead, Sun elected to increase the version number to 5 as a way of emphasizing
that a major event was taking place. Thus, the current product is called J2SE 5, and the
developer's kit is called JDK 5. However, in order to maintain consistency, Sun decided to
use 1.5 as its internal version number. Thus, 5 is the external version number and 1.5 is the
internal version number.
TERM LlflG
xxii Java: A Beginner's Guide
Because of Sun's use of 1.5 as the internal version number, when you ask the compiler its
version, it will respond with 1.5 rather than 5. Also, the online documentation supplied by
Sun uses 1.5 to refer to features added by the J2SE 5. In general, whenever you see 1.5, it
simply means 5.
This book has been fully updated to include the new features added by J2SE 5. To handle
all of the new material, two entirely new modules where added to this edition. Module 12
discusses enumerations, autoboxing, static import, and metadata. Module 13 examines generics.
Descriptions of the "for-each" style for loop and variable-length arguments were integrated
into existing modules.
This book presents an evenly paced tutorial in which each section builds upon the previous
one. It contains 14 modules, each discussing an aspect of Java. This book is unique because it
includes several special elements that reinforce what you are learning.
Each module begins with a set of critical skills that you will learn. The location of each skill
within the module is indicated.
Each module concludes with a Mastery Check, a self-test that lets you test your knowledge.
The answers are in Appendix A.
At the end of each major section, Progress Checks are presented which test your understanding
of the key points of the preceding section. The answers to these questions are at the bottom of
the page.
Sprinkled throughout the book are special "Ask the Expert" boxes. These contain additional
information or interesting commentary about a topic. They use a question-and-answer format.
How This Book Is Organized
Critical Skills
Mastery Check
Progress Checks
TERM LlflG
Preface xxiii
Projects
Each module contains one or more projects that show you how to apply what you are learning.
These are real-world examples that you can use as starting points for your own programs.
This book assumes no previous programming experience. Thus, if you have never programmed
before, you can use this book. If you do have some previous programming experience, you
will be able to advance a bit more quickly. Keep in mind, however, that Java differs in several
key ways from other popular computer languages. It is important not to jump to conclusions.
Thus, even for the experienced programmer, a careful reading is advised.
To compile and run the programs in this book, you will need the latest Java Development
Kit (JDK) from Sun, which at the time of this writing is Java 2 Platform Standard Edition,
version 5 (J2SE 5). Instructions for obtaining the Java JDK are given in Module 1.
If you are using an earlier version of Java, such as J2SE 1.4, then you will still be able to
use this book, but you won't be able to compile and run the programs that use the new features
addedbyJ2SE5.
Remember, the source code for all of the examples and projects in this book is available free
of charge on the Web at www.osborne.com.
No Previous Programming
Experience Required
Don't Forget: Code on the Web
TERM LlflG
xxiv Java: A Beginner's Guide
For Further Study
Java: A Beginner's Guide is your gateway to the Herb Schildt series of programming books.
Here are some others that you will find of interest.
To learn more about Java programming, we recommend the following:
Java: The Complete Reference, J2SE 5 Edition
• The Art of Java
To learn about C++, you will find these books especially helpful.
C++: The Complete Reference
Teach Yourself C+ +
C++ from the Ground Up
STL Programming from the Ground Up
The Art of C++
To learn about C#, we suggest the following Schildt books:
C#: A Beginner 's Guide
• C#: The Complete Reference
If you want to learn more about the C language, then the following titles will be of interest.
C: The Complete Reference
Teach Yourself C
When you need solid answers fast, turn to Herbert Schildt,
the recognized authority on programming.
TERM LlflG
Module 1
Java Fundamentals
CRITICAL SKILLS
1.1 Know the history and philosophy of Java
1.2 Understand Java's contribution to the Internet
1.3 Understand the importance of bytecode
1 .4 Know the Java buzzwords
1.5 Understand the foundational principles of object-oriented programming
1.6 Create, compile, and run a simple Java program
1.7 Use variables
1.8 Use the if and for control statements
1.9 Create blocks of code
1.10 Understand how statements are positioned, indented, and terminated
1.11 Know the Java keywords
1.12 Understand the rules for Java identifiers
Copyright © 2005 The McGraw-Hill Companies. Click here for terms of use.
1
TERM LiriG
2 Module 1 : Java Fundamentals
The rise of the Internet and the World Wide Web fundamentally reshaped computing. In
the past, the cyber landscape was dominated by stand-alone PCs. Today, nearly all PCs
are connected to the Internet. The Internet, itself, was transformed — originally offering a
convenient way to share files and information, today it is a vast, distributed computing universe.
With these changes came a new way to program: Java.
Java is the preeminent language of the Internet, but it is more than that. Java
revolutionized programming, changing the way that we think about both the form and the
function of a program. To be a professional programmer today implies the ability to program
in Java — it is that important. In the course of this book, you will learn the skills needed to
master it.
The purpose of this module is to introduce you to Java, including its history, its design
philosophy, and several of its most important features. By far, the hardest thing about learning a
programming language is the fact that no element exists in isolation. Instead, the components of
the language work in conjunction with each other. This interrelatedness is especially pronounced
in Java. In fact, it is difficult to discuss one aspect of Java without involving others. To help
overcome this problem, this module provides a brief overview of several Java features,
including the general form of a Java program, some basic control structures, and operators.
It does not go into too many details but, rather, concentrates on the general concepts common
to any Java program.
Computer language innovation is driven forward by two factors: improvements in the art of
programming and changes in the computing environment. Java is no exception. Building upon
the rich legacy inherited from C and C++, Java adds refinements and features that reflect the
current state of the art in programming. Responding to the rise of the online environment, Java
offers features that streamline programming for a highly distributed architecture.
Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and
Mike Sheridan at Sun Microsystems in 1991. This language was initially called "Oak" but
was renamed "Java" in 1995. Somewhat surprisingly, the original impetus for Java was not
the Internet! Instead, the primary motivation was the need for a platform-independent language
that could be used to create software to be embedded in various consumer electronic devices,
such as toasters, microwave ovens, and remote controls. As you can probably guess, many
different types of CPUs are used as controllers. The trouble was that most computer languages
are designed to be compiled for a specific target. For example, consider C++.
Although it is possible to compile a C++ program for just about any type of CPU, to do so
requires a full C++ compiler targeted for that CPU. The problem, however, is that compilers
are expensive and time-consuming to create. In an attempt to find a better solution, Gosling
CRITICAL SKILL
TERM LlflG
Java: A Beginner's Guide
and others worked on a portable, cross-platform language that could produce code that would
run on a variety of CPUs under differing environments. This effort ultimately led to the creation
of Java.
About the time that the details of Java were being worked out, a second, and ultimately
more important, factor emerged that would play a crucial role in the future of Java. This
second force was, of course, the World Wide Web. Had the Web not taken shape at about the
same time that Java was being implemented, Java might have remained a useful but obscure
language for programming consumer electronics. However, with the emergence of the Web,
Java was propelled to the forefront of computer language design, because the Web, too,
demanded portable programs.
Most programmers learn early in their careers that portable programs are as elusive as they
are desirable. While the quest for a way to create efficient, portable (platform-independent)
programs is nearly as old as the discipline of programming itself, it had taken a back seat to
other, more pressing problems. However, with the advent of the Internet and the Web, the old
problem of portability returned with a vengeance. After all, the Internet consists of a diverse,
distributed universe populated with many types of computers, operating systems, and CPUs.
What was once an irritating but a low-priority problem had become a high-profile necessity.
By 1993 it became obvious to members of the Java design team that the problems of
portability frequently encountered when creating code for embedded controllers are also found
when attempting to create code for the Internet. This realization caused the focus of Java to
switch from consumer electronics to Internet programming. So, while it was the desire for an
architecture-neutral programming language that provided the initial spark, it was the Internet
that ultimately led to Java's large-scale success.
How Java Relates to C and C++
Java is directly related to both C and C++. Java inherits its syntax from C. Its object model is
adapted from C++. Java's relationship with C and C++ is important for several reasons. First,
many programmers are familiar with the C/C++ syntax. This makes it easy for a C/C++
programmer to learn Java and, conversely, for a Java programmer to learn C/C++.
Second, Java's designers did not "reinvent the wheel." Instead, they further refined an
already highly successful programming paradigm. The modern age of programming began
with C. It moved to C++, and now to Java. By inheriting and building upon that rich heritage,
Java provides a powerful, logically consistent programming environment that takes the best of
the past and adds new features required by the online environment. Perhaps most important,
because of their similarities, C, C++, and Java define a common, conceptual framework for
the professional programmer. Programmers do not face major rifts when switching from one
language to another.
One of the central design philosophies of both C and C++ is that the programmer is in
charge! Java also inherits this philosophy. Except for those constraints imposed by the Internet
environment, Java gives you, the programmer, full control. If you program well, your programs
4 Module 1 : Java Fundamentals
reflect it. If you program poorly, your programs reflect that, too. Put differently, Java is not a
language with training wheels. It is a language for professional programmers.
Java has one other attribute in common with C and C++: it was designed, tested, and refined
by real, working programmers. It is a language grounded in the needs and experiences of the
people who devised it. There is no better way to produce a top-flight professional programming
language.
Because of the similarities between Java and C++, especially their support for object-
oriented programming, it is tempting to think of Java as simply the "Internet version of C++."
However, to do so would be a mistake. Java has significant practical and philosophical differences.
Although Java was influenced by C++, it is not an enhanced version of C++. For example, it
is neither upwardly nor downwardly compatible with C++. Of course, the similarities with
C++ are significant, and if you are a C++ programmer, you will feel right at home with Java.
Another point: Java was not designed to replace C++. Java was designed to solve a certain
set of problems. C++ was designed to solve a different set of problems. Both will coexist for
many years to come.
Recently a new language called C# has come on the scene. Created by Microsoft to support
its .NET Framework, C# is closely reated to Java. In fact, many of C#'s features were directly
adapted from Java. Both Java and C# share the same general C++-style syntax, support
distributed programming, and utilize the same object model. There are, of course, differences
between Java and C#, but the overall "look and feel" of these languages is very similar. This
means that if you already know C#, then learning Java will be especially easy. Conversely, if
C# is in your future, then your knowledge of Java will come in handy.
Given the similarity between Java and C#, one might naturally ask, "Will C# replace
Java?" The answer is No. Java and C# are optimized for two different types of computing
environments. Just as C++ and Java will co-exist for a long time to come, so will C# and Java.
How Java Relates to C#
1 . Java is useful for the Internet because it can produce
programs.
2. Java is the direct descendent of what languages?
1 . portable
2. C and C++.
TERM LlflG
Java: A Beginner's Guide
CRITICAL SKILL
Java's Contribution to the Internet
The Internet helped catapult Java to the forefront of programming, and Java, in turn, has had a
profound effect on the Internet. The reason for this is quite simple: Java expands the universe
of objects that can move about freely in cyberspace. In a network, there are two very broad
categories of objects that are transmitted between the server and your personal computer:
passive information and dynamic, active programs. For example, when you read your e-mail,
you are viewing passive data. Even when you download a program, the program's code is still
only passive data until you execute it. However, a second type of object can be transmitted to
your computer: a dynamic, self-executing program. Such a program is an active agent on the
client computer, yet it is initiated by the server. For example, a program might be provided by
the server to properly display the data that it is sending.
As desirable as dynamic, networked programs are, they also present serious problems in
the areas of security and portability. Prior to Java, cyberspace was effectively closed to half
of the entities that now live there. As you will see, Java addresses those concerns and, in doing
so, has defined a new form of program: the applet.
An applet is a special kind of Java program that is designed to be transmitted over the Internet
and automatically executed by a Java-compatible Web browser. Furthermore, an applet is
downloaded on demand, just like an image, sound file, or video clip. The important difference
is that an applet is an intelligent program, not just an animation or media file. In other words,
an applet is a program that can react to user input and dynamically change — not just run the
same animation or sound over and over.
As exciting as applets are, they would be nothing more than wishful thinking if Java
were not able to address the two fundamental problems associated with them: security and
portability. Before continuing, let's define what these two terms mean relative to the Internet.
As you are almost certainly aware, every time you download a "normal" program, you are
risking a viral infection. Prior to Java, most users did not download executable programs
frequently, and those that did, scanned them for viruses prior to execution. Even so, most users
still worried about the possibility of infecting their systems with a virus or allowing a malicious
program to run wild in their systems. (A malicious program might gather private information,
such as credit card numbers, bank account balances, and passwords by searching the contents
of your computer's local file system.) Java answers these concerns by providing a firewall
between a networked application and your computer.
6 Module 1 : Java Fundamentals
When using a Java-compatible web browser, it is possible to safely download Java applets
without fear of viral infection. The way that Java achieves this is by confining a Java program
to the Java execution environment and not allowing it access to other parts of the computer.
(You will see how this is accomplished, shortly.) Frankly, the ability to download applets with
confidence that no harm will be done to the client computer is the single most important aspect
of Java.
As discussed earlier, many types of computers and operating systems are connected to the
Internet. For programs to be dynamically downloaded to all of the various types of platforms,
some means of generating portable executable code is needed. As you will soon see, the same
mechanism that helps ensure security also helps create portability. Indeed, Java's solution to
these two problems is both elegant and efficient.
The key that allows Java to solve both the security and the portability problems just described
is that the output of a Java compiler is not executable code. Rather, it is bytecode. Bytecode
is a highly optimized set of instructions designed to be executed by the Java run-time system,
which is called the Java Virtual Machine (JVM). That is, the Java Virtual Machine is an
interpreter for bytecode. This may come as a bit of a surprise. As you know, most modern
languages, such as C++, are designed to be compiled, not interpreted — mostly because of
performance concerns. However, the fact that a Java program is executed by the JVM helps
solve the major problems associated with downloading programs over the Internet. Here is why.
Translating a Java program into bytecode makes it much easier to run a program in a wide
variety of environments. The reason is straightforward: only the Java Virtual Machine needs to
be implemented for each platform. Once the run-time package exists for a given system, any
Java program can run on it. Remember that although the details of the JVM will differ from
platform to platform, all understand the same Java bytecode. If a Java program were compiled
to native code, then different versions of the same program would have to exist for each type
of CPU connected to the Internet. This is, of course, not a feasible solution. Thus, the
interpretation of bytecode is the easiest way to create truly portable programs.
The fact that a Java program is interpreted also helps m
Lire la suite
- 9.77 MB
- 15
Vous recherchez le terme ""

50

30

51