Java in 21 Days [PDF]

Introduction. Day 1 An Introduction to Java Programming · What Is Java? Java's Past, Present, and Future · Why Learn Jav

3 downloads 17 Views 376KB Size

Recommend Stories


[PDF] Download Java in 21 Days, Sams Teach Yourself
You're not going to master the rest of your life in one day. Just relax. Master the day. Than just keep

Winter Schools (21 Days)
The happiest people don't have the best of everything, they just make the best of everything. Anony

21 days of
Don't be satisfied with stories, how things have gone with others. Unfold your own myth. Rumi

21 Days Countdown
Live as if you were to die tomorrow. Learn as if you were to live forever. Mahatma Gandhi

21 Days of Prayer
Silence is the language of God, all else is poor translation. Rumi

[PDF] Pass Pmp in 21 Days: Practice Tests
We may have all come on different ships, but we're in the same boat now. M.L.King

21 Days to Health & Beyond
Ask yourself: Do I love myself as much as I expect others to love me? Next

PdF Java 8 in Action
The best time to plant a tree was 20 years ago. The second best time is now. Chinese Proverb

21 Days of Prayer & Fasting January 1-21, 2016
Live as if you were to die tomorrow. Learn as if you were to live forever. Mahatma Gandhi

Sodium Swap Change Your Salty Ways in 21 Days Infographic
Why complain about yesterday, when you can make a better tomorrow by making the most of today? Anon

Idea Transcript


Teach Yourself

Java in 21 Days Professional Reference Edition

by Laura Lemay, Charles L. Perkins and Michael Morrison

C O N T E N T S Introduction Day 1 An Introduction to Java Programming What Is Java? Java's Past, Present, and Future Why Learn Java? Java Is Platform Independent Java Is Object Oriented Java Is Easy to Learn Getting Started Programming in Java Getting a Java Development Environment Installing the JDK and Sample Files Configuring the JDK Creating a Java Application Creating a Java Applet Troubleshooting Summary Q&A

Day 2 Object-Oriented Programming and Java Thinking in Objects: An Analogy Objects and Classes Behavior and Attributes Attributes Behavior Creating a Class Inheritance, Interfaces, and Packages Inheritance Creating a Class Hierarchy How Inheritance Works Single and Multiple Inheritance Interfaces and Packages Creating a Subclass Summary Q&A

Day 3 Java Basics Statements and Expressions Variables and Data Types Declaring Variables Notes on Variable Names Variable Types Assigning Values to Variables Comments Literals Number Literals Boolean Literals Character Literals String Literals Expressions and Operators Arithmetic More About Assignment Incrementing and Decrementing Comparisons Logical Operators Bitwise Operators Operator Precedence String Arithmetic Summary Q&A

Day 4 Working with Objects Creating New Objects Using new What new Does A Note on Memory Management Accessing and Setting Class and Instance Variables Getting Values Changing Values Class Variables Calling Methods Class Methods References to Objects Casting and Converting Objects and Primitive Types Casting Primitive Types Casting Objects Converting Primitive Types to Objects and Vice Versa Odds and Ends Comparing Objects Determining the Class of an Object Class and Object Reflection (Java 1.1) The Java Class Library Summary Q&A

Day 5 Arrays, Conditionals, and Loops Arrays Declaring Array Variables Creating Array Objects Accessing Array Elements Changing Array Elements Multidimensional Arrays Block Statements if Conditionals The Conditional Operator switch Conditionals for Loops while and do Loops while Loops do...while Loops Breaking Out of Loops Labeled Loops Summary Q&A

Day 6 Creating Classes and Applications in Java Defining Classes Creating Instance and Class Variables Defining Instance Variables Constants Class Variables Creating Methods Defining Methods The this Keyword Variable Scope and Method Definitions Passing Arguments to Methods Class Methods Creating Java Applications Helper Classes Java Applications and Command-Line Arguments Passing Arguments to Java Programs Handling Arguments in Your Java Program Summary Q&A

Day 7 More About Methods Creating Methods with the Same Name, Different Arguments Constructor Methods Basic Constructors Calling Another Constructor Overloading Constructors Overriding Methods Creating Methods That Override Existing Methods Calling the Original Method Overriding Constructors Finalizer Methods Summary Q&A

Day 8 Java Applet Basics How Applets and Applications Are Different Creating Applets Major Applet Activities A Simple Applet Including an Applet on a Web Page The Tag Testing the Result Making Java Applets Available to the Web More About the Tag ALIGN HSPACE and VSPACE CODE and CODEBASE

Java Archives Passing Parameters to Applets Summary Q&A

Day 9 Graphics, Fonts, and Color The Graphics Class The Graphics Coordinate System Drawing and Filling Lines Rectangles Polygons Ovals Arcs A Simple Graphics Example Copying and Clearing Text and Fonts Creating Font Objects Drawing Characters and Strings Finding Out Information About a Font Color Using Color Objects Testing and Setting the Current Colors A Simple Color Example Summary Q&A

Day 10 Simple Animation and Threads Creating Animation in Java Painting and Repainting Starting and Stopping an Applet's Execution The Missing Link: Threads Putting It Together Threads: What They Are and Why You Need Them Writing Applets with Threads Another Look at the Digital Clock Reducing Animation Flicker Flicker and How to Avoid It How to Override update() Solution One: Don't Clear the Screen Solution Two: Redraw Only What You Have To Summary Q&A

Day 11 More Animation, Images, and Sound Retrieving and Using Images Getting Images Drawing Images A Note About Image Observers Modifying Images Creating Animation Using Images An Example: Neko Retrieving and Using Sounds Using Animation Packages Sun's Animator Applet Dimension X's Liquid Motion More About Flicker: Double-Buffering Creating Applets with Double-Buffering A Note on Disposing Graphics Contexts An Example: Checkers Revisited Summary Q&A

Day 12 Managing Simple Events and Interactivity Mouse Clicks Mouse Down and Mouse Up Events An Example: Spots Double-Clicks Mouse Movements Mouse Drag and Mouse Move Events Mouse Enter and Mouse Exit Events An Example: Drawing Lines Keyboard Events The keyDown() and keyUp() Methods Default Keys An Example: Entering, Displaying, and Moving Characters Testing for Modifier Keys and Multiple Mouse Buttons The awt Event Handler Summary Q&A

Day 13 Creating User Interfaces with the awt An awt Overview The Basic User Interface Components Labels Buttons Check Boxes Radio Buttons Choice Menus Text Fields Panels and Layout Layout Managers: An Overview The FlowLayout Class Grid Layouts Border Layouts Card Layouts Grid Bag Layouts Insets Handling UI Actions and Events Nesting Panels and Components Nested Panels Events and Nested Panels More UI Components Text Areas Scrolling Lists Scrollbars and Sliders Canvases More UI Events Fun with Components A Complete Example: RGB-to-HSB Converter Designing and Creating the Applet Layout Defining the Subpanels Handling the Actions Updating the Result The Complete Source Code Up and Coming in Java 1.1 Summary Q&A

Day 14 Windows, Networking, and Other Tidbits Windows, Menus, and Dialog Boxes The awt Window Classes Frames Closing Windows Menus Dialog Boxes Cursors Window Events Standalone awt Applications Networking in Java Creating Links Inside Applets Opening Web Connections openStream()

Sockets Changes to Sockets for Java 1.1 Other Applet Hints The showStatus() Method Applet Information Communicating Between Applets Summary Q&A

Day 15 Modifiers, Access Control, and Class Design Modifiers Controlling Access to Methods and Variables Why Access Control Is Important The Four Ps of Protection Method Protection and Inheritance Instance Variable Protection and Accessor Methods Class Variables and Methods Finalizing Classes, Methods, and Variables Finalizing Classes Finalizing Variables Finalizing Methods Abstract Classes and Methods Summary Q&A

Day 16 Packages and Interfaces Programming in the Large and Programming in the Small What Are Packages? Using Packages Full Package and Class Names The import Command Name Conflicts A Note About CLASSPATH and Where Classes Are Located Creating Your Own Packages Pick a Package Name Create the Directory Structure Use package to Add Your Class to a Package Packages and Class Protection What Are Interfaces? The Problem of Single Inheritance Abstract Design and Concrete Implementation Interfaces and Classes Implementing and Using Interfaces The implements Keyword Implementing Multiple Interfaces Other Uses of Interfaces Creating and Extending Interfaces New Interfaces Methods Inside Interfaces Extending Interfaces An Example: Enumerating Linked Lists Summary Q&A

Day 17 Exceptions Exceptions, the Old and Confusing Way Java Exceptions Managing Exceptions Exception Consistency Checking Protecting Code and Catching Exceptions The finally Clause Declaring Methods That Might Throw Exceptions The throws Clause Which Exceptions Should You Throw? Passing On Exceptions throws and Inheritance Creating and Throwing Your Own Exceptions Throwing Exceptions Creating Your Own Exceptions Doing It All: Combining throws, try, and throw When and When Not to Use Exceptions When to Use Exceptions When Not to Use Exceptions Bad Style Using Exceptions Summary Q&A

Day 18 Multithreading Thread Fundamentals The Problem with Parallelism Thinking Multithreaded Points About Points Protecting a Class Variable Creating and Using Threads The Runnable Interface ThreadTester NamedThreadTester

Knowing When a Thread Has Stopped Thread Scheduling Preemptive Versus Nonpreemptive Testing Your Scheduler Summary Q&A

Day 19 Streams and I/O What Are Streams? The java.io Package Input Streams The Abstract Class InputStream ByteArrayInputStream FileInputStream FilterInputStream PipedInputStream SequenceInputStream StringBufferInputStream

Output Streams The Abstract Class OutputStream ByteArrayOutputStream FileOutputStream FilterOutputStream PipedOutputStream

Related Classes Object Serialization (Java 1.1) Summary Q&A

Day 20 Using Native Methods and Libraries Why Use Native Methods? Advantages of Using Native Methods Disadvantages of Native Methods The Illusion of Required Efficiency Design First, Efficiency Later Just-in-Time Compilers Simple Optimization Tricks Writing Native Methods Write Your Java Code Generate Header and Stub Files Implementing the Native Library Using Your Library Tools and Techniques for Writing Native Implementations Names Accessing Java Objects Calling Methods Creating New Java Objects Handling Exceptions Dealing with Strings Summary Q&A

Day 21 Under the Hood -The Big Picture Why It's a Powerful Vision The Java Virtual Machine An Overview The Fundamental Parts The Constant Pool Limitations The Bytecode Interpreter Just-in-Time Compilers The Class File Format Method Signatures The Garbage Collector The Problem The Solution Java's Parallel Garbage Collector The Security Story Why You Should Worry Why You Might Not Have To Java's Applet Security Model Signed Applets Coming Up in Java 1.1 Summary Q&A

Day 22 Java Programming Tools Overview of the Standard JDK Tools The Runtime Interpreter Usage The OptionsArgument The Non-Optimized Interpreter The Compiler Usage The OptionsArgument The Non-Optimizing Compiler The Applet Viewer Usage The OptionsArgument Commands Profiling Java Applets The Debugger Usage The OptionsArgument Commands The Class File Disassembler Usage The OptionsArgument The Header and Stub File Generator Usage The OptionsArgument The Documentation Generator Usage The OptionsArgument Documentation Tags Visual Development Tools Sun's Java WorkShop Symantec Café Microsoft Visual J++ Natural Intelligence's Roaster Rogue Wave Software's JFactory Penumbra Software's Mojo Aimtech's Jamba Kinetix's Hyperwire Summary Q&A

Day 23 Working with Data Structures in Java Data Structure Fundamentals The Standard Java Data Structures Enumerations Bit Sets Vectors Stacks Dictionaries Hash Tables Building Your Own Data Structures Linked List Basics Implementing a Linked List Summary Q&A

Day 24 Advanced Animation and Media What Is Animation? Types of Animation Frame-Based Animation Cast-Based Animation Tracking Images The MediaTracker Class Implementing Sprite Animation The Sprite Class The SpriteVector Class The Background Classes Sample Applet: Sharks Summary Q&A

Day 25 Fun with Image Filters The Basics of Color Color Images in Java Color Models Direct Color Models Index Color Models The Color Model Classes Image Filters The Image Filter Classes Writing Your Own Image Filters A Color Image Filter An Alpha Image Filter A Brightness Image Filter Using Image Filters Summary Q&A

Day 26 Client/Server Networking in Java Internet Network Basics Addresses Protocols Ports The Client/Server Paradigm Sockets Datagram Sockets Stream Sockets Fortune: A Datagram Client and Server Designing Fortune Implementing the Fortune Server Implementing the Fortune Client Applet Running Fortune Trivia: A Stream Client and Server Designing Trivia Implementing the Trivia Server Implementing the Trivia Client Applet Running Trivia Summary Q&A

Day 27 The Standard Extension APIs Java API Overview The Enterprise API Java Database Connectivity Interface Definition Language Remote Method Invocation The Commerce API The Management API The Server API The Media API The Security API The Java Beans API The Embedded API Summary Q&A

Day 28 Emerging Technologies Java Beans The Goal of Java Beans How Java Beans Relates to Java The Java Beans API JavaOS Overhead Industry Support Java Microprocessors picoJAVA microJAVA UltraJAVA Summary Q&A

appendix A Language Summary Reserved Words Comments Literals Variable Declaration Variable Assignment Operators Objects Arrays Loops and Conditionals Class Definitions Method and Constructor Definitions Packages, Interfaces, and Importing Exceptions and Guarding

appendix B Class Hierarchy Diagrams About These Diagrams

appendix C The Java Class Library java.lang

Interfaces Classes java.util

Interfaces Classes java.io

Interfaces Classes java.net

Interfaces Classes java.awt

Interfaces Classes java.awt.image

Interfaces Classes java.awt.peer java.applet

Interfaces Classes

appendix D Bytecodes Reference The _quick Bytecodes

appendix E java.applet Package Reference AppletContext AppletStub AudioClip Applet

appendix F java.awt Package Reference LayoutManager MenuContainer BorderLayout Button Canvas CardLayout Checkbox CheckboxGroup CheckboxMenuItem Choice Color Component Container Dialog Dimension Event FileDialog FlowLayout Font FontMetrics Frame Graphics GridBagConstraints GridBagLayout GridLayout Image Insets Label List MediaTracker Menu MenuBar MenuComponent MenuItem Panel Point Polygon Rectangle Scrollbar TextArea TextComponent TextField Toolkit Window awtException awtError

appendix G java.awt.image Package Reference ImageConsumer ImageObserver ImageProducer ColorModel CropImageFilter DirectColorModel FilteredImageSource ImageFilter IndexColorModel MemoryImageSource PixelGrabber RGBImageFilter

appendix H java.awt.peer Package Reference ButtonPeer CanvasPeer CheckboxMenuItemPeer CheckboxPeer ChoicePeer ComponentPeer ContainerPeer DialogPeer FileDialogPeer FramePeer LabelPeer ListPeer addItem MenuBarPeer MenuComponentPeer MenuItemPeer MenuPeer PanelPeer ScrollbarPeer TextAreaPeer TextComponentPeer TextFieldPeer WindowPeer

appendix I java.io Package Reference DataInput DataOutput FilenameFilter BufferedInputstream BufferedOutputStream ByteArrayInputStream ByteArrayOutputStream DataInputStream DataOutputStream File FileDescriptor FileInputStream FileOutputStream FilterInputStream FilterOutputStream InputStream LineNumberInputStream OutputStream PipedInputStream PipedOutputStream PrintStream PushbackInputStream RandomAccessFile SequenceInputStream StreamTokenizer StringBufferInputStream EOFException FileNotFoundException IOException InterruptedIOException UTFDataFormatException

appendix J java.lang Package Reference Cloneable Runnable Boolean Character Class ClassLoader Compiler Double Float Integer Long Math Number Object Process Runtime SecurityManager String StringBuffer System Thread ThreadGroup Throwable RuntimeException ClassNotFoundException CloneNotSupportedException Exception IllegalAccessException IllegalArgumentException IllegalMonitorStateException IllegalThreadStateException IndexOutOfBoundsException InstantiationException InterruptedException NegativeArraySizeException NullPointerException NumberFormatException RuntimeException SecurityException StringIndexOutOfBoundsException AbstractMethodError ClassFormatError Error IllegalAccessError IncompatibleClassChangeError InstantiationError InternalError LinkageError NoClassDefFoundError NoSuchFieldError NoSuchMethodError OutOfMemoryError StackOverflowError ThreadDeath UnknownError UnsatisfiedLinkError VerifyError VirtualMachineError

appendix K java.net Package Reference ContentHandlerFactory SocketImplFactory URLStreamHandlerFactory ContentHandler DatagramPacket DatagramSocket InetAddress ServerSocket Socket SocketImpl URL URLConnection URLEncoder MalformedURLException ProtocolException SocketException UnknownHostException UnknownServiceException

appendix L java.util Package Reference Enumeration Observer BitSet Date Dictionary Hashtable Observable Properties Random Stack StringTokenizer Vector EmptyStackException NoSuchElementException

Credits Copyright © 1996 by Sams.net Publishing All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Neither is any liability assumed for damages resulting from the use of the information contained herein. For information, address Sams.net Publishing, 201 W. 103rd St., Indianapolis, IN 46290. International Standard Book Number: 1-57521-183-1 HTML conversion by : M/s. LeafWriters (India) Pvt. Ltd. Website : http://leaf.stpn.soft.net e-mail : [email protected]

Credits President, Sams Publishing

Richard K. Swadley

Publishing Manager

Mark Taber

Managing Editor

Cindy Morrow

Director of Marketing

John Pierce

Assistant Marketing Managers

Kristina Perry, Rachel Wolfe

Acquisitions Editor

Mark Taber

Software Development Specialist Bob Correll

Development Editor

Fran Hatton

Senior Editor

Kitty Wilson

Technical Edit Coordinator

Kimberly K. Hannel, Colleen Indexer Williams Brad Birnbaum, Pratip Banerji, Jeff Editorial Coordinator Bankston, Jeff Shockley, Lorraine Schaffer Editorial Assistants

Cover Designer

Tim Amrhein

Book Designer

Carol Ackerman, Andi Richter, Rhonda Tinch-Mize Gary Adair

Copy Writer

Peter Fuller

Production Team Supervisor

Brad Chinn

Production

Cynthia Davis, Elizabeth Deeter, Sonja Hart, Lousia Klucznik, Polly Lavrick, Paula Lowell, Andrew Stone

Copy Editors Technical Reviewers

Johnna VanHoose Bill Whitmer

Preface to the Professional Reference Edition I first saw Java running in May of 1995, and was immediately struck by what it offered to the Web. What I saw seems almost quaint in this day and age of multimedia Web pages-a small animation of a character doing cartwheels across the screen-but at the time it was a revolution. My friend Jim Graham, a programmer on the Java team, showed me various aspects of the Java language and the HotJava browser, and I sat with my mouth agape, unable to say much of anything except for "that is so cool." At the time, I was just finishing up a book about HTML and looking for something else to do. I immediately knew that this had to be it. I had to write a book on Java. It took somewhat longer to actually produce the book, between needing to finish a number of other projects, having to wait for a new version of Java itself, and coming down with a number of bad cases of the flu, but the book was written and shipped in early 1996. That book was the original Teach Yourself Java in 21 Days. While not the first book available on the Java language, it was widely regarded as the first good book and the first one that wasn't either too vague or that assumed too much knowledge of programming. Written for an intermediate programmer, Teach Yourself Java continues to be one of the few books available that offers a basic tutorial in Java, enough to get you started and enough to move beyond the basics. Teach Yourself Java continues to be popular and continues to be recommended as one of the best books on getting started in Java. Which brings us to this hefty tome that you're holding in your hands. Since early 1996 Java itself has not changed overly much. The current 1.0.2 release has added few features since 1.0; for the new features we'll have to wait for 1.1 (due out in late 1996). But given the explosion of tools for building Java applications and the wide variety of things that people are doing with Java out there for the Web and for general-purpose applications, there is no shortage of things to talk about when it comes to Java. This book, therefore, is an extension of the original Teach Yourself Java. It has been greatly expanded and enhanced, with all the original content updated, the weak parts fixed, and more examples added. This book also contains a bonus week that adds further depth and detail about existing topics such as images, animation, and networking; it includes information about tools, debugging, and advanced data structures; and it goes into great detail about upcoming features in Java 1.1 and the extension APIs. With more than 250 pages of reference material, there's little you won't be able to discover using this book. If you haven't yet worked with Java, this is the book to start with. If you have worked with Java but are looking for more information, this is the book to continue with. And even if you've read the original Teach Yourself Java, you'll find enough new in this edition to merit putting aside the original and adding this one to the stack of programming books on your desk. Good luck and enjoy! Laura Lemay August 1996

Acknowledgments From Laura Lemay: To Sun's Java team, for all their hard work on Java, the language, and on the browser, and particularly to Jim Graham, who demonstrated Java and HotJava to me on very short notice in May and planted the idea for this book. To everyone who bought my previous books and liked them: Buy this one, too. From Charles L. Perkins: To Patrick Naughton, who first showed me the power and the promise of Oak (Java) in early 1993. To Mark Taber, who shepherded this lost sheep through his first book. From Mike Morrison: Thanks to Mark Taber for giving me the opportunity to contribute to such a cool project, and to Fran Hatton for being so enormously positive and helpful.

About the Authors Laura Lemay Laura Lemay is a technical writer and a nerd. After spending six years writing software documentation for various computer companies in Silicon Valley, she decided that writing books would be much more fun (but has still not yet made up her mind). In her spare time she collects computers, e-mail addresses, interesting hair colors, and nonrunning motorcycles. She is also the perpetrator of Teach Yourself Web Publishing with HTML in 14 Days. You can visit her home page at http://www.lne.com/lemay/. Charles L. Perkins Charles L. Perkins is the founder of Virtual Rendezvous, a company building a Java-based service that will foster socially focused, computer-mediated, real-time filtered interactions between people's personas in the virtual environments of the near future. In previous lives, he has evangelized NeXTSTEP, SmallTalk, and UNIX, and has degrees in both physics and computer science. Before attempting this book, he was an amateur columnist and author. He's done research in speech recognition, neural nets, gestural user interfaces, computer graphics, and language theory, but had the most fun working at Thinking Machines and Xerox PARC's SmallTalk group. In his spare time, he reads textbooks for fun. You can reach him via e-mail at [email protected], or visit his Java page at http://rendezvous.com/java. Michael Morrison Michael Morrison is the author of Teach Yourself Internet Game Programming with Java in 21 Days, and a contributing author to Tricks of the Java Programming Gurus, Java Unleashed, and Game Developer magazine. Michael lives in Scottsdale, Arizona, with his (now legally recognized) female cohort, Mahsheed. In his spare time, Michael enjoys testing his threshold for pain on skateboard ramps. You can reach Michael via e-mail at [email protected], or check out his Web site at http://www.thetribe.com.

Tell Us What You Think! As a reader, you are the most important critic and commentator of our books. We value your opinion and want to know what we're doing right, what we could do better, what areas you'd like to see us publish in, and any other words of wisdom you're willing to pass our way. You can help us make strong books that meet your needs and give you the computer guidance you require. Do you have access to CompuServe or the World Wide Web? Then check out our CompuServe forum by typing GO SAMS at any prompt. If you prefer the World Wide Web, check out our site at http://www.mcp.com. Note If you have a technical question about this book, call the technical support line at 800-571-5840, ext. 3668. As the team leader of the group that created this book, I welcome your comments. You can fax, e-mail, or write me directly to let me know what you did or didn't like about this book-as well as what we can do to make our books stronger. Here's the information: 317-581-4669 FAX: E-mail: [email protected] Mail:

Mark Taber Publishing Manager Sams.net Publishing 201 W. 103rd Street Indianapolis, IN 46290

Introduction The World Wide Web, for much of its existence, has been a method for distributing passive information to a widely distributed number of people. The Web has, indeed, been exceptionally good for that purpose. With the addition of forms and image maps, Web pages began to become interactive-but the interaction was often simply a new way to get at the same information. The limitations of Web distribution were all too apparent once designers began to try to stretch the boundaries of what the Web can do. Even other innovations, such as Netscape's server push to create dynamic animations, were merely clever tricks layered on top of a framework that wasn't built to support much other than static documents with images and text. Enter Java, and the capability for Web pages to contain Java applets. Applets are small programs that create animations, multimedia presentations, real-time (video) games, multiuser networked games, and real interactivity-in fact, most anything a small program can do, Java applets can. Downloaded over the Net and executed inside a Web page by a browser that supports Java, applets are an enormous step beyond standard Web design. The disadvantage of Java is that to create Java applets right now, you need to write them in the Java language. Java is a programming language, and therefore, creating Java applets is more difficult than creating a Web page or a form using HTML. Soon there will be tools and programs that will make creating Java applets easier-they may be available by the time you read this. For now, however, the only way to delve into Java is to learn the language and start playing with the raw Java code. Even when the tools come out, you may want to do more with Java than the tools can provide, and you're back to learning the language. That's whereTeach Yourself Java in 21 Days comes in. This book teaches you all about the Java language and how to use it to create not only applets, but also applications, which are more general Java programs that don't need to run inside a Web browser. By the time you get through with this book, you'll know enough about Java to do just about anything, inside an applet or out. How This Book Is Organized Teach Yourself Java in 21 Days covers the Java language and its class libraries in 21 days, organized as three separate weeks. In addition, this edition contains a bonus week that's chock full of new and advanced information. Each week covers a different broad area of developing Java applets and applications. In the first week you'll learn about the Java language itself: Day 1 is the basic introduction: what Java is, why it's cool, and how to get the software. You'll also create your first Java applications and applets. On Day 2 you'll explore basic object-oriented programming concepts as they apply to Java. On Day 3 you'll start getting down to details with the basic Java building blocks: data types, variables, and expressions, such as arithmetic and comparisons. Day 4 goes into detail about how to deal with objects in Java: how to create them, how to access their variables and call their methods, and how to compare and copy them. You'll also get your first glance at the Java class libraries. On Day 5 you'll learn more about Java, with arrays, conditional statements, and loops. Day 6 is the best one yet. You'll learn how to create classes, the basic building blocks of any Java program, and how to put together a Java application (a Java program that can run on its own without a Web browser). Day 7 builds on what you learned on Day 6. You'll learn more about how to create and use methods, including overriding and overloading methods and creating constructors. Week 2 is dedicated to applets and the Java class libraries: Day 8 provides the basics of applets-how they're different from applications, how to create them, and about the most important parts of an applet's life cycle. You'll also learn how to create HTML pages that contain Java applets. On Day 9 you'll learn about the Java classes for drawing shapes and characters to the screen-in black, white, or any other color. On Day 10 you'll start animating those shapes you learned about on Day 9, including learning about threads and their uses. Day 11 covers more detail about animation, adding bitmap images and audio to the soup. Day 12 delves into interactivity-handling mouse and keyboard clicks from the user in your Java applets. Day 13 is ambitious; you'll learn about using Java's Abstract Windowing Toolkit to create a user interface in your applet, including menus, buttons, check boxes, and other elements. On Day 14 you'll explore the last of the main Java class libraries for creating applets: windows and dialogs, networking, and a few other tidbits. Week 3 includes advanced topics for when you start doing larger and more complex Java programs or when you want to learn more: On Day 15 you'll learn more about the Java language's modifiers-for abstract and final methods and classes as well as for protecting a class's private information from the prying eyes of other classes. Day 16 covers interfaces and packages, useful for abstracting protocols of methods to aid reuse and for the grouping and categorization of classes. Day 17 covers exceptions: errors and warnings and other abnormal conditions, generated either by the system or by you in your programs. Day 18 builds on the thread basics you learned on Day 10 to give a broad overview of multithreading and how to use it to allow different parts of your Java programs to run in parallel. On Day 19 you'll learn all about the input and output streams in Java's I/O library. Day 20 teaches you about native code-how to link C code into your Java programs to provide missing functionality or to gain performance. On Day 21 you'll get an overview of some of the behind-the-scenes technical details of how Java works: the bytecode compiler and interpreter, the techniques Java uses to ensure the integrity and security of your programs, and the Java garbage collector. This Professional Reference Edition also includes a bonus week that contains more depth about some of the topics previously mentioned in the book, lots more sample programs, and coverage of the various tools and utilities currently available for writing with Java. It also gives you a preview of the features coming up in Java 1.1: Day 22 describes tools and utilities for programming in Java, including debugging techniques, Java development environments such as Symantec Café and Visual J++, the javadoc documentation system, and other tips and tricks. On Day 23 you'll learn about creating structures for modeling various forms of data, both with the classes in the java.util package and by creating new classes. Day 24 goes into even more detail about animation in Java, building on the simple techniques covered in Week 2. On this day you'll learn about creating sprite-based animation and coordinating image and media loading with your programs. Sun's java.awt.image package provides a set of classes for working with images. Day 25 covers these classes in detail, explaining the image filter architecture and how you can use it in your own Java programs. Day 14 gives a very basic introduction to networking in Java. Day 26 takes it further, with extensive examples of networking applets and applications, working with "live" data sent from a server, and connecting to databases from Java applets. On Day 27 we move into the future and describe what are known as the standard extension APIs. Sun is developing these APIs in conjunction with other interested parties, and many of the features you'll learn about in this chapter will be part of the 1.1 Java API. Day 28 finishes up with more future topics, including Sun's Java Beans API, Java chips, and the JavaOS. How will these technologies affect how you work in Java and how Java will affect you? Learn about it here as you finish up the book.

Preparing for the Future: The Upcoming Java 1.1 Release At the time this book is being written, the current version of Java is known as the 1.0 API (or, more exactly, the 1.0.2 version of the JDK). A new version of Java is on the horizon, one that will add a significant number of new features to Java while still being backward compatible with the original version. This new version of Java, called Java 1.1, is expected to be available in a prerelease form in late 1996. This book covers the Java 1.0 API in intimate detail. Where information about an upcoming feature of 1.1 is available, we have attempted to explain that new feature, how it will affect what you have already learned about the 1.0 API, and where to look for further information. In addition, the last two chapters of this book cover the more advanced features of 1.1 and how they will be used. These notes and comments will help you prepare for when 1.1 is released and help you migrate the code you may have already written quickly and easily to the new API. Features expected to be in the 1.1 JDK include JDBC (the Java Database Connectivity interface) provides a mechanism for connecting Java applications and applets to SQL databases such as Oracle and Sybase. The JDBC, available in a prerelease form at this time from http://splash.javasoft.com/jdbc/, is covered on Day 27. RMI (Remote Method Invocation) is the ability to call a Java method from an object running elsewhere (for example, in a different Java environment running on the same machine or on any machine on the network). RMI is closely related to object serialization, which allows objects to be encoded into a stream of bytes, which can then be sent over a network or saved to a file. The result can then also be decoded back into a Java object at the other end. Object serialization is an extension of the stream classes discussed on Day 19. RMI is discussed in greater detail on Day 27. Information about both of these topics can be found at http://chatsubo.javasoft.com/current/. The Java native methods interface is the ability for Java to call system-specific libraries such as DLLs or loadable libraries written in C. Writing native methods is described on Day 20; enhancement in Java 1.1 will include a better API for making sure native method libraries are compatible with every implementation of the Java runtime across platforms. JIT compilers are tools that convert Java bytecode to native machine code. You'll learn about JIT compilers throughout this book, but particularly on Days 21 and 22. In Java 1.1 there will be better specifications for writing your own JIT or other tool that generates native code from Java bytecodes. Changes to the awt. Probably some of the more significant changes to Java will be in the area of the Abstract Windowing Toolkit, or awt, the portion of Java that controls drawing to the screen, creating user interface elements such as buttons and windows, and handling painting and user input between all those elements. This book covers the awt primarily in Week 2. Enhancements to the awt in Java 1.1 include printing, pop-up menus, supports for clipboards (copy and paste), internationalization for fonts, better scrolling capabilities, and delegation-based events. You'll learn more about these changes throughout Week 2. Security enhancements. JDK 1.1 will provide many features for implementing security in Java applications, including signatures, access control, key management, and message digests (MD5 hashes, for example). These additions won't affect much of 1.0 because they are new enhancements. You'll learn all about 1.1's security features on Day 27. Networking enhancements. Java 1.0 provides the java.net classes, which provide simple network connections, URL management, and simple client and server sockets. Java 1.1 provides more flexibility for the existing socket classes, a new MulticastSocket class, and BSD-style socket options. Learn about all these new features on Day 14 or from the URL http://java.sun.com/products/JDK/1.1/designspecs/net/index.html. Adapter classes allow you to implement an API defined by an interface or a class and have the flow of control move from the adapter class back to an enclosing object. Java 1.1 provides Java syntax for nesting class definitions inside other class definitions to more easily create adapter classes. You'll learn more on Day 6. Object reflection is the ability for Java to inspect an object and find out its methods and variables (and call and change them). Object reflection is useful for class browsers or other tools that need to find out information about an object on-the-fly, as well as component object systems that need defined ways of referring to other objects' contents. Java 1.1 provides many features for handling object reflection, including a number of new classes. You'll find out more on Day 4 or from http://java.sun.com/products/JDK/1.1/designspecs/reflection/index.html. Java 1.1 provides a number of new features for internationalization, particularly language-specific features such as strings, character set conversions, Unicode character display, and support for definable "locales." Java archives (JAR files) provide a mechanism for combining several classes into a single file for faster downloading over the Net. Netscape provides a single archive file mechanism for applets, but JAR files provide a more cross-platform file format, compression, and the ability to include media files in the archive. The capability to store Java classes in JAR files, and to use them with Java-enabled browsers, will be in Java 1.1. The current JAR file format specification is available from http://java.sun.com/security/codesign/jarformat.html. You can learn more about all these features via information throughout this book or from the Java 1.1 preview page at http://www.java.sun.com/products/JDK/1.1/designspecs/.

Conventions Used in This Book Text that you type and text that should appear on your screen is presented in monospace type: It will look like this.

It mimics the way text looks on your screen. Placeholders for variables and expressions appear in monospace italic. The end of each chapter offers common questions asked about that day's subject matter, with answers from the authors.

Sources for Further Information Before, while, and after you read this book, there are several Web sites that may be of interest to you as a Java developer. The official Java Web site is at http://java.sun.com/. At this site, you'll find the Java development software and online documentation for all aspects of the Java language, including the previously mentioned Java 1.1 preview page. It has several mirror sites that it lists online, and you should probably use the site "closest" to you on the Internet for your downloading and Java Web browsing. There is also an excellent site for developer resources, called Gamelan, at http://www.gamelan.com/, which contains an enormous number of applets and applications, with sample code, help, and plenty of information about Java and Java development. This book also has a companion Web site at http://www.lne.com/Web/JavaProf/. Information at that site includes examples, more information, and background for this book, corrections to this book, and other tidbits that are not included here. For discussion about the Java language and the tools to develop in it, check out the Usenet newsgroups for comp.lang.java. This set of newsgroups-which includes comp.lang.java.programming, comp.lang.java.api, comp.lang.java.misc, comp.lang.java.security, and comp.lang.java.tech-is a terrific source for getting questions answered and for keeping up on new Java developments.

Praise for Teach Yourself Java "If you get only one Java book, it should be Teach Yourself Java in 21 Days. Authors Laura Lemay and Charles L. Perkins cover all aspects of Java programming in an easy-to-read guide organized around daily lesson plans." -Jay Munro, pc Magazine "…this is where to begin. Java in all its gory details: classes to applets, methods to multithreading." -Thom Gillespie, Library Journal "Teach Yourself Java gives a thoughtful treatment to under-the-hood issues of Java's implementation." -Peter Coffee, pc Week "If you buy one book on Java, this is the one to buy. Teach Yourself Java is one of the best introductions to hands-on Java programming. The setup of the book is extremely well thought out." -Scott Sidel, Independent Web Review "This is the best introduction to object-oriented programming ever written. This book does not assume that you know C or C++, but it offers tips for those who do. Laura Lemay is my favorite tech author.…If you can afford only one Java book, then this is the one to get." -David Geary

What's New in This Edition Given the explosion of tools for building Java applications and the wide variety of things that people are doing with Java, for the Web and for general-purpose applications, there is no shortage of new things to talk about when it comes to Java. This edition, therefore, is a fully revised and extended edition of the original Teach Yourself Java in 21 Days. It has been greatly expanded and enhanced, with all the original content updated, the weak parts fixed, and more examples added. This edition also contains a bonus week that adds further depth and detail about existing topics such as images, animation, and networking, as well as information about tools, debugging, and advanced data structures. In the bonus week you'll also learn about the following: Day 22 describes tools and utilities for programming in Java, including debugging techniques, Java development environments such as Symantec Café and Visual J++, the javadoc documentation system, and other tips and tricks. Day 23 covers creating structures for modeling various forms of data, both with the classes in the java.util package and by creating new classes. Day 24 goes into even more detail about animation in Java, building on the simple techniques covered in Week 2. Sun's java.awt.image package provides a set of classes for working with images. Day 25 covers these classes in detail, explaining the image filter architecture and how you can use it in your own Java programs. Day 26 takes a further look at client/server networking, with extensive examples of networking applets and applications and working with live data sent from a server, as well as connecting to databases from Java applets. Days 27 and 28 move into the future and describe what are known as the standard extension APIs. Many of the features you'll learn about on Day 27 will be part of Java 1.1. Day 28 finishes up with more future topics, including Sun's Java Beans API, Java chips, and the JavaOS. The bonus week goes into great detail about upcoming features in Java 1.1 and the extension APIs. And with more than 250 pages of reference material in the appendixes, there's little you won't be able to discover using this book.

About This Book This book teaches you all about the Java language and how to use it to create applets for the World Wide Web, as well as standalone applications. By the time you get through with this book, you'll know enough about Java and about the Java class libraries to do just about anything, inside an applet or out.

Who Should Read This Book This book is intended for people with at least some basic programming background, which includes people with years of programming experience and people with only a small amount of experience. If you understand what variables, loops, and functions are, you'll be just fine for this book. The sorts of people who might want to read this book include you, if You're a real whiz at HTML, understand CGI programming (in Perl, AppleScript, Visual Basic, or some other popular CGI language) pretty well, and want to move on to the next level in Web page design. You had some BASIC or Pascal in school and you have a basic grasp of what programming is, but you've heard Java is easy to learn, really powerful, and very cool. You've programmed C and C++ for many years, you've heard this Java thing is becoming really popular, and you're wondering what all the fuss is about. You've heard that Java is really good for Web-based applets, and you're curious about how good it is for creating more general applications. What if you know programming, but you don't know object-oriented programming? Fear not. This book assumes no background in object-oriented design. If you know object-oriented programming, in fact, the first couple days will be easy for you. What if you're a rank beginner? This book might move a little fast for you. Java is a good language to start with, though, and if you take it slow and work through all the examples, you may still be able to pick up Java and start creating your own applets.

How This Book Is Structured This book is intended to be read and absorbed over the course of four weeks. During each week, you'll read seven chapters that present concepts related to the Java language and the creation of applets and applications.

Conventions Note A note box presents interesting pieces of information related to the surrounding discussion.

Technical Note A technical note presents specific technical information related to the surrounding discussion.

Tip A tip box offers advice or teaches an easier way to do something.

Warning A warning box advises you about potential problems and helps you steer clear of disaster.

New terms New terms are introduced in new term boxes, with the new term in italics.

Type A type icon identifies some new Java code that you can type in. You can also get the code from the CD-ROM that accompanies this book.

Output An output icon shows the output from a Java program.

Analysis An analysis icon alerts you to the author's line-by-line analysis.

Smile Life

When life gives you a hundred reasons to cry, show life that you have a thousand reasons to smile

Get in touch

© Copyright 2015 - 2024 PDFFOX.COM - All rights reserved.