Java™ in 60 Minutes a Day
Java™ in 60 Minutes a Day
Richard F. Raposa
Executive Publisher: Robert Ipsen Vice President and Publisher: Joe Wikert Senior Editor: Ben Ryan Editorial Manager: Kathryn A. Malm Developmental Editor: Jerry Olsen Production Editor: Vincent Kunkemueller Media Development Specialist: Angie Denny Text Design & Composition: Wiley Composition Services Copyright © 2003 by Richard F. Raposa. All rights reserved. Published by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning, or otherwise, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8700. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4447, E-mail:
[email protected]. Limit of Liability/Disclaimer of Warranty: While the publisher and author have used their best efforts in preparing this book, they make no representations or warranties with respect to the accuracy or completeness of the contents of this book and specifically disclaim any implied warranties of merchantability or fitness for a particular purpose. No warranty may be created or extended by sales representatives or written sales materials. The advice and strategies contained herein may not be suitable for your situation. You should consult with a professional where appropriate. Neither the publisher nor author shall be liable for any loss of profit or any other commercial damages, including but not limited to special, incidental, consequential, or other damages. For general information on our other products and services please contact our Customer Care Department within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002. Trademarks: Wiley, the Wiley logo and related trade dress are trademarks or registered trademarks of Wiley in the United States and other countries, and may not be used without written permission. The Gearhead Press trademark is the exclusive property of Gearhead Group Corporation. Java is a trademark of Sun Microsystems, Inc. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books. Library of Congress Cataloging-in-Publication Data: See Publisher ISBN: 0-471-42314-9 Printed in the United States of America 10 9 8 7 6 5 4 3 2 1
A Note from the Consulting Editor Instructor-led training is proven to be an effective and popular tool for training engineers and developers. To convey technical ideas and concepts, the classroom experience is shown to be superior when compared to other delivery methods. As a technical trainer for more than 20 years, I have seen the effectiveness of instructor-led training firsthand. 60 Minutes a Day combines the best of the instructor-led training and book experience. Technical training is typically divided into short and discrete modules, where each module encapsulates a specific topic; each module is then followed by “questions and answers” and a review. 60 Minutes a Day titles follow the same model: each chapter is short, discrete, and can be completed in 60 minutes a day. For these books, I have enlisted premier technical trainers as authors. They provide the voice of the trainer and demonstrate classroom experience in each book of the series. You even get an opportunity to meet the actual trainer: As part of this innovative approach, each chapter of a 60 Minutes a Day book is presented online by the author. Readers are encouraged to view the online presentation before reading the relevant chapter. Therefore, 60 Minutes a Day delivers the complete classroom experience—even the trainer. As an imprint of Wiley Publishing, Inc., Gearhead Press continues to bring you, the reader, the level of quality that Wiley has delivered consistently for nearly 200 years.
Thank you. Donis Marshall Founder, Gearhead Press Consulting Editor, Wiley Technology Publishing Group
To my wife, Susan, for her motivation and support, and to our children, Megan, Ryan, Katelyn, and Emma, for letting me use the computer for hours at a time.
Contents
Acknowledgments
xix
About the Author
xxi
Introduction Chapter 1
xxiii Getting Started with Java Why Java? The Java Virtual Machine The Editions of Java J2SE J2ME J2EE
4 5 5
Downloading the Java 2 SDK Installing the SDK Running the SDK Tools
6 7 8
Running the javac Compiler Running the JVM
9 10
A Simple Java Program Step 1: Write the Source Code Step 2: Compile the Program Step 3: Run the Program
Chapter 2
1 1 2 4
10 11 13 14
Summary
17
Java Fundamentals Java Keywords Identifiers Java’s Eight Primitive Data Types Variables
21 21 22 23 24
Assigning Variables
Integral Types
25
27 ix
x
Contents Floating-Point Types Boolean Data Type Char Data Type Strings References versus Primitive Data Constants Java Operators Increment and Decrement Operators Assignment Operators Shift Operators Comparison Operators Boolean Operators Ternary Operator
Chapter 3
39 40 40 42 43 43
Java Comments Summary
44 46
Control Structures Flow of Control Boolean Logic
51 51 52
The and Operator The or Operator The exclusive or Operator The not Operator
Chapter 4
29 30 31 33 35 37 37
52 53 54 54
Boolean Operators The if Statement The if/else Statement The switch Statement The while Loop The do/while Loop The for Loop The break Keyword The continue Keyword Nested Loops Summary
55 57 59 61 64 67 70 74 76 78 80
Classes and Objects Overview of Classes and Objects Procedural Programming Object-Oriented Programming Object-Oriented Analysis and Design Writing a Java Class
85 85 86 87 88 89
Adding Fields to a Class Adding Methods to a Class
89 90
Instantiating an Object Garbage Collection Accessing Fields and Methods Using the Dot Operator
92 94 97 97
Step 1: Write the Employee Class Step 2: Compile the Employee Class
97 98
Contents Step 3: Write the EmployeeDemo Class Step 4: Compile the EmployeeDemo class Step 5: Run the EmployeeDemo program
Chapter 5
The this Reference Summary
100 103
Methods Method Call Stack Invoking Methods Method Signature Arguments and Parameters Call-by-Value Overloading Methods Constructors Default Constructor Using Constructors
107 107 108 111 113 116 121 125 128 129
A Class with Multiple Constructors
Chapter 6
130
Using this in a Constructor Summary
131 136
Understanding Inheritance An Overview of Inheritance The is a Relationship Implementing Inheritance Instantiating Child Objects Single versus Multiple Inheritance The java.lang.Object Class The Methods of the Object Class Method Overriding The super Keyword The final Keyword
139 139 144 145 146 149 150 151 154 157 160
final Methods
Chapter 7
98 99 99
161
The Instantiation Process Invoking a Parent Class Constructor Summary
162 165 170
Advanced Java Language Concepts An Overview of Packages Adding a Class to a Package The Namespace Created by Packages The import Keyword The Directory Structure of Packages
175 175 176 178 180 183
Step 1: Write and Save the Source Code for Vehicle Step 2: Compile the Source Code Using the -d Flag Step 3: Write the CarDealer Class Step 4: Set the CLASSPATH Step 5: Compile and Run the CarDealer Program
The Access Specifiers Encapsulation
185 185 186 187 188
190 194
xi
xii
Contents Benefits of Encapsulation Understanding Static Members Accessing Static Fields and Methods Static Initializers Instance Initializers Summary
197 198 199 203 205 209
Chapter 8
Polymorphism and Abstraction An Overview of Polymorphism Using Parent Class References to Child Objects Casting References The instanceof Keyword Polymorphic Parameters Heterogeneous Collections Virtual Methods Taking Advantage of Virtual Methods An Overview of Abstraction Abstract Classes Abstract Methods Summary
213 213 214 218 221 225 229 230 233 238 239 241 247
Chapter 9
Collections Arrays Accessing Arrays The length Attribute Arrays of References Array Initializers Copying Arrays Multidimensional Arrays Example of a Heterogeneous Collection Overview of the Java Collections Framework The Vector Class
253 253 255 255 256 259 261 263 265 272 273
Adding Elements to a Vector Accessing and Removing Elements in a Vector
The Hashtable Class Adding Elements to a Hashtable Accessing Elements in a Hashtable
Summary Chapter 10 Interfaces An Overview of Interfaces Declaring Interfaces User-Defined Interfaces Write the Interface Source Code Compile the Interface
Implementing an Interface Write a Class That Implements Paintable Save and Compile the Rectangle Class Add the paint() Method Write a Class That Uses Paintable
275 277
281 283 285
290 295 295 296 298 299 299
300 300 301 302 302
Contents Using Interfaces Exposing Methods via an Interface Forcing Behavior on a Class Declaring Fields in Interfaces Extending Interfaces Extending Multiple Interfaces
Interfaces and Polymorphism Summary
303 304 310 316 317 319
321 326
Chapter 11 Exception Handling Overview of Exception Handling Flow of Control of Exceptions Throwable Classes Methods of the Throwable Class Catching Exceptions Writing try/catch Blocks Multiple catch Blocks Handle or Declare Rule Declaring Exceptions The throws Keyword Throwing Exceptions The finally Keyword Overridden Methods and Exceptions User-Defined Exceptions Summary
329 329 330 333 333 334 335 337 341 343 345 348 351 354 357 361
Chapter 12 An Introduction to GUI Programming AWT versus Swing Creating Windows
367 367 369
java.awt.Frame Class javax.swing.JFrame Class
369 372
Containers and Components
375
Adding Components to a Container
Layout Managers FlowLayout Manager BorderLayout Manager Panels GridLayout Manager BoxLayout Manager Nesting Panels Using No Layout Manager Summary Chapter 13 GUI Components and Event Handling The Delegation Model The Event Listener Interfaces Creating an Event Listener Registering a Listener with an Event Source The Event Adapter Classes
375
378 379 383 385 388 390 392 396 401 405 405 407 409 410 412
xiii
xiv
Contents Buttons AWT Buttons Swing Buttons
Check Boxes AWT Check Boxes Swing Check Boxes
Radio Buttons AWT Radio Buttons Swing Radio Buttons
Labels Text Components AWT Text Components Swing Text Components
Lists
417 417 418
421 421 423
425 425 427
429 430 430 434
437
AWT Lists Swing Lists
437 439
Combo Boxes
440
AWT Choice Swing Combo Boxes
Progress Bars Menus Summary Chapter 14 Applets An Overview of Applets The java.applet.Applet Class Swing Applets Life Cycle of an Applet Step 1: Write the Applet Class Step 2: Write the HTML Page Step 3: View the HTML Page Step 4: View the Java Console
The