195 33 4MB
English Pages 672 [664] Year 2006;2008
Java Tutorial
THE
TM
Fourth Edition A Short Course on the Basics
This page intentionally left blank
Java Tutorial
THE
TM
Fourth Edition A Short Course on the Basics
Sharon Zakhour Scott Hommel Jacob Royal Isaac Rabinovitch Tom Risser Mark Hoeber
ADDISON-WESLEY Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Capetown • Sydney • Tokyo • Singapore • Mexico City
Copyright © 1996–2006 Sun Microsystems, Inc. 4150 Network Circle, Santa Clara, California 95054 U.S.A. All rights reserved. Duke logo™ designed by Joe Palrang. RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by the United States Government is subject to the restrictions set forth in DFARS 252.227–7013 (c)(1)(ii) and FAR 52.227–19. The release described in this manual may be protected by one or more U.S. patents, foreign patents, or pending applications. Sun Microsystems, Inc. (SUN) hereby grants to you a fully paid, nonexclusive, nontransferable, perpetual, worldwide limited license (without the right to sublicense) under SUN’s intellectual property rights that are essential to practice this specification. This license allows and is limited to the creation and distribution of clean room implementations of this specification that: (i) include a complete implementation of the current version of this specification without subsetting or supersetting; (ii) implement all the interfaces and functionality of the required packages of the Java™ 2 Platform, Standard Edition, as defined by SUN, without subsetting or supersetting; (iii) do not add any additional packages, classes, or interfaces to the java.* or javax.* packages or their subpackages; (iv) pass all test suites relating to the most recent published version of the specification of the Java™ 2 Platform, Standard Edition, that are available from SUN six (6) months prior to any beta release of the clean room implementation or upgrade thereto; (v) do not derive from SUN source code or binary materials; and (vi) do not include any SUN source code or binary materials without an appropriate and separate license from SUN. Sun, Sun Microsystems, the Sun logo, Solaris, Java, JavaScript, JDK, the Duke logo, JVM, JRE, JavaBeans, NetBeans, JDBC, and all Java-based trademarks or logos are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. UNIX is a registered trademark in the United States and other countries, exclusively licensed through X/Open Company, Ltd. THIS PUBLICATION IS PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. THIS PUBLICATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN; THESE CHANGES WILL BE INCORPORATED IN NEW EDITIONS OF THE PUBLICATION. SUN MICROSYSTEMS, INC. MAY MAKE IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED IN THIS PUBLICATION AT ANY TIME. The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. For more information, please contact: U.S. Corporate and Government Sales (800) 382–3419 [email protected] For sales outside the United States please contact: International Sales [email protected]
This Book Is Safari Enabled The Safari® Enabled icon on the cover of your favorite technology book means the book is available through Safari Bookshelf. When you buy this book, you get free access to the online edition for 45 days. Safari Bookshelf is an electronic reference library that lets you easily search thousands of technical books, find code samples, download chapters, and access technical information whenever and wherever you need it. To gain 45-day Safari Enabled access to this book: • Go to http://www.awprofessional.com/safarienabled • Complete the brief registration form • Enter the coupon code S1KU-LBNJ-GNTJ-WAJT-PZJV If you have difficulty registering on Safari Bookshelf or accessing the online edition, please e-mail [email protected]. Visit us on the Web: www.awprofessional.com Library of Congress Cataloging-in-Publication Data The Java tutorial : a short course on the basics / Sharon Zakhour... [et al.]. -- 4th ed. p. cm. Previous ed: The Java tutorial / by Mary Campione. Includes index. ISBN 0-321-33420-5 (pbk. : alk. paper) 1. Java (Computer program language) I. Zakhour, Sharon. II. Campione, Mary. Java tutorial. QA76.73.J38C365 2006 005.13'3--dc22
2006028544
All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding permissions, write to: Pearson Education, Inc. Rights and Contracts Department 75 Arlington Street, Suite 300 Boston, MA 02116 Fax: (617) 848–7047 ISBN 0–321–33420–5 Text printed in the United States on recycled paper at RR Donnelley in Crawfordsville, Indiana. First printing, October 2006
This page intentionally left blank
Contents
Foreword ...................................................................................................... xix Preface ......................................................................................................... xxi Chapter 1
Getting Started ............................................................................................
1
The Java Technology Phenomenon 1 About the Java Technology 1 What Can Java Technology Do? 4 How Will Java Technology Change My Life? 5 The “Hello World!” Application 6 “Hello World!” for the NetBeans IDE 6 “Hello World!” for Microsoft Windows 14 “Hello World!” for Solaris OS and Linux 19 A Closer Look at the “Hello World!” Application 24 Source Code Comments 24 The HelloWorldApp Class Definition 25 The main Method 25 Common Problems (and Their Solutions) 27 Compiler Problems 27 Runtime Problems 29 Questions and Exercises: Getting Started 30 Chapter 2
Object-Oriented Programming Concepts ................................................ What Is an Object? 33 What Is a Class? 35 What Is Inheritance? 37 What Is an Interface? 38 What Is a Package? 39 Questions and Exercises: Object-Oriented Programming Concepts
33
40
vii
viii
CONTENTS
Chapter 3
Language Basics .......................................................................................... Variables 43 Naming 44 Primitive Data Types 45 Arrays 49 Summary of Variables 53 Questions and Exercises: Variables 54 Operators 55 Assignment, Arithmetic, and Unary Operators 56 Equality, Relational, and Conditional Operators 59 Bitwise and Bit Shift Operators 62 Summary of Operators 63 Questions and Exercises: Operators 64 Expressions, Statements, and Blocks 66 Expressions 66 Statements 67 Blocks 68 Questions and Exercises: Expressions, Statements, and Blocks Control Flow Statements 69 The if-then and if-then-else Statements 69 The switch Statement 71 The while and do-while Statements 74 The for Statement 75 Branching Statements 77 Summary of Control Flow Statements 82 Questions and Exercises: Control Flow Statements 82
Chapter 4
68
Classes and Objects .................................................................................... Classes 85 Declaring Classes 87 Declaring Member Variables 88 Defining Methods 90 Providing Constructors for Your Classes 92 Passing Information to a Method or a Constructor 93 Objects 97 Creating Objects 99 Using Objects 103 More on Classes 106 Returning a Value from a Method 106 Using the this Keyword 109 Controlling Access to Members of a Class 110 Understanding Instance and Class Members 112
43
85
ix
CONTENTS
Initializing Fields 117 Summary of Creating and Using Classes and Objects Questions and Exercises: Classes 119 Questions and Exercises: Objects 121 Nested Classes 122 Why Use Nested Classes? 122 Static Nested Classes 123 Inner Classes 123 Inner Class Example 124 Summary of Nested Classes 127 Questions and Exercises: Nested Classes 128 Enum Types 128 Questions and Exercises: Enum Types 132 Annotations 132 Documentation 133 Annotations Used by the Compiler 134 Annotation Processing 136 Questions and Exercises: Annotations 136 Chapter 5
118
Interfaces and Inheritance ......................................................................... 139 Interfaces 139 Interfaces in Java 140 Interfaces as APIs 141 Interfaces and Multiple Inheritance 141 Defining an Interface 142 Implementing an Interface 143 Using an Interface as a Type 145 Rewriting Interfaces 146 Summary of Interfaces 146 Questions and Exercises: Interfaces 147 Inheritance 147 The Java Platform Class Hierarchy 148 An Example of Inheritance 148 What You Can Do in a Subclass 150 Private Members in a Superclass 151 Casting Objects 151 Overriding and Hiding Methods 152 Hiding Fields 154 Using the Keyword super 154 Object as a Superclass 156 Writing Final Classes and Methods 160 Abstract Methods and Classes 161
x
CONTENTS
Summary of Inheritance 164 Questions and Exercises: Inheritance Chapter 6
164
Generics ....................................................................................................... 167 Introduction 167 A Simple Box Class 168 Generic Types 169 Type Parameter Conventions 171 Generic Methods and Constructors 172 Bounded Type Parameters 173 Subtyping 175 Wildcards 177 Type Erasure 178 Summary of Generics 179 Questions and Exercises: Generics 180
Chapter 7
Packages ....................................................................................................... 183 Creating and Using Packages 183 Creating a Package 184 Naming a Package 186 Using Package Members 187 Managing Source and Class Files 191 Summary of Creating and Using Packages 193 Questions and Exercises: Creating and Using Packages
Chapter 8
194
Numbers and Strings .................................................................................. 195 Numbers 195 The Numbers Classes 195 Formatting Numeric Print Output 198 Beyond Basic Arithmetic 203 Summary of Numbers 208 Questions and Exercises: Numbers 209 Characters 210 Escape Sequences 212 Strings 212 Creating Strings 213 String Length 213 Concatenating Strings 214 Creating Format Strings 215 Converting Between Numbers and Strings 216 Manipulating Characters in a String 218 Comparing Strings and Portions of Strings 224
xi
CONTENTS
The StringBuilder Class 226 Summary of Characters and Strings 230 Questions and Exercises: Characters and Strings Chapter 9
231
Exceptions .................................................................................................... 233 What Is an Exception? 233 The Catch or Specify Requirement 235 The Three Kinds of Exceptions 235 Bypassing Catch or Specify 236 Catching and Handling Exceptions 236 The try Block 238 The catch Blocks 239 The finally Block 240 Putting It All Together 241 Specifying the Exceptions Thrown by a Method 245 How to Throw Exceptions 246 The throw Statement 247 Throwable Class and Its Subclasses 247 Error Class 248 Exception Class 248 Chained Exceptions 249 Creating Exception Classes 250 Unchecked Exceptions—The Controversy 252 Advantages of Exceptions 253 Advantage 1: Separating Error-Handling Code from “Regular” Code Advantage 2: Propagating Errors Up the Call Stack 255 Advantage 3: Grouping and Differentiating Error Types 257 Summary 258 Questions and Exercises: Exceptions 259
253
Chapter 10 Basic I/O ...................................................................................................... 261 I/O Streams 261 Byte Streams 263 Character Streams 265 Buffered Streams 269 Scanning and Formatting 270 I/O from the Command Line 276 Data Streams 279 Object Streams 282 File I/O 286 File Objects 286 Random Access Files 289
xii
CONTENTS
The New I/O Packages 291 Summary 292 Questions and Exercises: Basic I/O
292
Chapter 11 Collections ................................................................................................... 293 Introduction to Collections 293 What Is a Collections Framework? 294 Benefits of the Java Collections Framework 294 Interfaces 295 The Collection Interface 298 The Set Interface 301 The List Interface 306 The Queue Interface 316 The Map Interface 319 Object Ordering 328 The SortedSet Interface 335 The SortedMap Interface 338 Summary of Interfaces 340 Questions and Exercises: Interfaces 340 Implementations 342 Set Implementations 344 List Implementations 346 Map Implementations 347 Queue Implementations 349 Wrapper Implementations 350 Convenience Implementations 352 Summary of Implementations 354 Questions and Exercises: Implementations 355 Algorithms 355 Sorting 356 Shuffling 358 Routine Data Manipulation 359 Searching 359 Composition 360 Finding Extreme Values 360 Custom Collection Implementations 360 Reasons to Write an Implementation 360 How to Write a Custom Implementation 361 Interoperability 364 Compatibility 364 API Design 366
xiii
CONTENTS
Chapter 12 Concurrency ................................................................................................ 369 Processes and Threads 369 Processes 370 Threads 370 Thread Objects 371 Defining and Starting a Thread 371 Pausing Execution with sleep 372 Interrupts 373 Joins 375 The SimpleThreads Example 375 Synchronization 377 Thread Interference 377 Memory Consistency Errors 379 Synchronized Methods 380 Intrinsic Locks and Synchronization 381 Atomic Access 383 Liveness 384 Deadlock 384 Starvation and Livelock 385 Guarded Blocks 386 Immutable Objects 391 A Synchronized Class Example 391 A Strategy for Defining Immutable Objects High-Level Concurrency Objects 395 Lock Objects 395 Executors 397 Concurrent Collections 400 Atomic Variables 401 For Further Reading 402 Questions and Exercises: Concurrency 403
393
Chapter 13 Regular Expressions ................................................................................... 405 Introduction 405 What Are Regular Expressions? 405 How Are Regular Expressions Represented in This Package? Test Harness 406 String Literals 407 Metacharacters 408 Character Classes 409 Simple Classes 410 Predefined Character Classes 414 Quantifiers 416
406
xiv
CONTENTS
Zero-Length Matches 417 Capturing Groups and Character Classes with Quantifiers 420 Differences among Greedy, Reluctant, and Possessive Quantifiers Capturing Groups 422 Numbering 422 Backreferences 423 Boundary Matchers 424 Methods of the Pattern Class 425 Creating a Pattern with Flags 426 Embedded Flag Expressions 427 Using the matches(String,CharSequence) Method 428 Using the split(String) Method 428 Other Utility Methods 430 Pattern Method Equivalents in java.lang.String 430 Methods of the Matcher Class 431 Index Methods 431 Study Methods 431 Replacement Methods 432 Using the start and end Methods 432 Using the matches and lookingAt Methods 434 Using replaceFirst(String) and replaceAll(String) 434 The appendReplacement(StringBuffer,String) and appendTail(StringBuffer) Methods 436 Matcher Method Equivalents in java.lang.String 436 Methods of the PatternSyntaxException Class 437 Summary 439 Additional Resources 440 Questions and Exercises: Regular Expressions 440
421
Chapter 14 The Platform Environment ........................................................................ 443 Configuration Utilities 443 Properties 443 Command-Line Arguments 448 Environment Variables 449 Other Configuration Utilities 451 System Utilities 452 Command-Line I/O Objects 452 System Properties 452 The Security Manager 455 Miscellaneous Methods in System 457 PATH and CLASSPATH 457 Update the PATH Variable (Microsoft Windows NT/2000/XP)
458
CONTENTS
Update the PATH Variable (Solaris and Linux) 458 Checking the CLASSPATH Variable (All Platforms) 460 Questions and Exercises: The Platform Environment 460 Chapter 15 Swing ............................................................................................................ 463 A Brief Introduction to the Swing Package 463 What Is Swing? 463 A Swing Demo 466 Swing Features 470 A Visual Guide to Swing Components 470 Pluggable Look and Feel 476 Drag and Drop and Data Transfer 480 Internationalization and Localization 480 Accessibility 482 Integrating with the Desktop 483 System Tray Icon Support 484 Questions: Graphical User Interfaces 485 Chapter 16 Packaging Programs in JAR Files ............................................................. 487 Using JAR Files: The Basics 488 Creating a JAR File 490 Viewing the Contents of a JAR File 493 Extracting the Contents of a JAR File 495 Updating a JAR File 496 Running JAR-Packaged Software 498 Working with Manifest Files: The Basics 500 Understanding the Default Manifest 500 Modifying a Manifest File 501 Setting an Application’s Entry Point 502 Adding Classes to the JAR File’s Classpath 503 Setting Package Version Information 504 Sealing Packages Within a JAR File 506 Signing and Verifying JAR Files 507 Understanding Signing and Verification 508 Signing JAR Files 511 Verifying Signed JAR Files 513 Using JAR-Related APIs 514 An Example—The JarRunner Application 514 The JarClassLoader Class 515 The JarRunner Class 518 Questions: JAR Files 520
xv
xvi
CONTENTS
Chapter 17 Java Web Start ............................................................................................ 521 Running Java Web Start Applications 522 Running a Java Web Start Application from a Browser 523 Running an Application from the Java Cache Viewer 523 Running a Java Web Start Application from the Desktop 524 Deploying Java Web Start Applications 524 Setting Up the Web Server 525 Creating the JNLP File 525 Placing the Application on the Web Server 533 Creating the Web Page 534 Developing Java Web Start Applications 534 Packaging the Application in JAR Files 534 Reading Resources in a JAR File 535 Untrusted Applications 535 The JNLP API 536 Java Web Start and Security 538 Java Web Start Security Basics 538 Signing JAR Files for Java Web Start Deployment 538 Security and JNLP Files 538 Dynamic Downloading of HTTPS Certificates 539 Common Java Web Start Problems 539 Questions and Exercises: Java Web Start 540 Chapter 18 Applets ......................................................................................................... 543 Getting Started with Applets 545 Extending Applet or JApplet 546 The Life Cycle of an Applet 547 Methods for Milestones 550 Methods for Drawing and Event Handling 552 Methods for Adding UI Components 554 What Applets Can and Can’t Do 558 Taking Advantage of the Applet API 559 Finding and Loading Data Files 560 Displaying Short Status Strings 561 Displaying Documents in the Browser 562 Sending Messages to Other Applets 564 Playing Sounds 568 Defining and Using Applet Parameters 570 Using the APPLET Tag 574 Practical Considerations When Writing Applets 578 Security Restrictions 578 Creating a User Interface 581
xvii
CONTENTS
Getting System Properties 583 Threads in Applets 585 Working with a Server-Side Application 589 Finishing an Applet 593 Before You Ship That Applet 593 The Perfectly Finished Applet 594 Deploying Applets 594 General Deployment Considerations 595 Using the applet Tag 595 Using the object Tag 596 Using the embed Tag 598 Deploying Applets in a Mixed-Browser Environment Solving Common Applet Problems 600 Questions and Exercises: Java Applets 602
598
Appendix A Java Language Keywords .......................................................................... 603 Appendix B Preparation for Java Programming Language Certification .................. 605 Index ............................................................................................................. 617
This page intentionally left blank
Foreword
I
T is with some pleasure that I write this foreword to the new edition of the Java Tutorial.
One of the distinguishing characteristics of the Java platform has been the quality of its documentation. This has included the tutorials, as well as the detailed documentation of the APIs by means of JavaDoc, and the many books published in the Java series. One could argue that the quality of the documentation resources has been every bit as important to the widespread adoption of the Java platform as the quality of the language and libraries themselves. Indeed, they are all of a piece, and each deserves recognition and credit for the qualities it manifests. Millions of developers spend their professional lives enveloped in the ecosystem engendered by the Java platform. There are myriad standards, APIs and tools. There is so much to learn! What’s more, the amount of information you need to know keeps on growing. While this growth is something we software professionals should all be thankful for, it is an ongoing challenge for developers. I hope this tutorial will make it easier to meet this challenge and obtain competence and even mastery of the Java platform. Whether you become a truly “competent programmer,” as Edsger Dijkstra put it many years ago, is up to you; but if you don’t, it cannot be blamed on the lack of a good Java tutorial. A number of dedicated professionals have done their best to see to that. I hope this new edition meets and even exceeds the high standards set by its predecessors. Ultimately, it is you, the reader, who must be the judge. I expect you will not be disappointed. Gilad Bracha Los Altos, California June 2006
xix
This page intentionally left blank
Preface
SINCE the release of the original Java Development Kit in May of 1995, the engineering team at Sun Microsystems has been hard at work improving and enhancing the Java platform. The publication of this edition coincides with the release of Version 6 of the Java Platform Standard Edition (Java SE) and reflects the API of that release. This edition introduces new features added to the Java platform since the publication of the third edition (under release 1.3), such as a chapter on Generics and information on annotations. There are new chapters on Java Web Start, The Platform Environment, and Regular Expressions. Most chapters, such as Concurrency (formerly Threads), I/O, Object-Oriented Programming Concepts, and Language Basics, have been completely rewritten. Collections has been brought out of the appendix and into its own chapter. A new appendix contains information on how to prepare for the Java Programming Language Certification exam. All of the material has been thoroughly reviewed by members of engineering to ensure that the information is accurate and up to date. Like the previous editions, this book is based on the online tutorial hosted at Sun Microsystems’ Web site: http://java.sun.com/docs/books/tutorial/
The information in this book is—often referred to as “the core tutorial” or “the basics”—that are required by most beginning to intermediate programmers. Once you have mastered the material in this book, you can explore the rest of the Java platform on the Web site. As always, our goal is to create an easy-to-read practical programmer’s guide with lots of examples to help people learn to program.
xxi
xxii
PREFACE
Who Should Read This Book? This book is geared towards both novice and experienced programmers. • New programmers can benefit most from reading the book from beginning to end, including the step by step instructions for compiling and running your first program in Getting Started (page 1). • Programmers experienced with procedural languages such as C++ may wish to start with the material on object-oriented concepts and features of the Java programming language. • Experienced programmers may want to jump feet first into more advanced topics, such as generics, concurrency, or Java Web Start. This book contains information to address the learning needs of programmers with various levels of experience.
How to Use This Book This book is designed so you can read it straight through or skip around from topic to topic. The information is presented in a logical order, and forward references are avoided wherever possible. The examples in this tutorial are compiled against the 6.0 release. You need to download this release in order to compile and run most examples. The accompanying CD contains the content of this book (including examples, and solutions and answers to the questions and exercises), as well as the online-only Java SE tutorials, an early 6.0 release of the Java SE Development Kit (JDK), and the corresponding API specification and guide documentation. You will see footnotes like the following: docs/api/java/lang/Class.html
and tutorial/deployment/applet/examples/TalkServer.java
The highest level of the CD contains docs and tutorial directories, so those footnotes can be located on the CD as specified. To locate the latest pages online, prepend http://java.sun.com/javase/6/ to the docs footnotes and http://java.sun.com/docs/books/ to the tutorial footnotes:
PREFACE
http://java.sun.com/javase/6/docs/api/java/lang/Class.html http://java.sun.com/docs/books/tutorial/deployment/applet/ examples/TalkServer.java
The chapters in this book can be found on the CD at the following locations: Chapter
Location
1. Getting Started
tutorial/getStarted
2. Object-Oriented Programming Concepts
tutorial/java/concepts
3. Language Basics
tutorial/java/nutsandbolts
4. Classes and Objects
tutorial/java/javaOO
5. Interfaces and Inheritance
tutorial/java/IandI
6. Generics
tutorial/java/generics
7. Packages
tutorial/java/package
8. Numbers and Strings
tutorial/java/data
9. Exceptions
tutorial/essential/exceptions
10. Basic I/O
tutorial/essential/io
11. Collections
tutorial/collections
12. Concurrency
tutorial/essential/concurrency
13. Regular Expressions
tutorial/essential/regex
14. The Platform Environment
tutorial/essential/environment
15. Swing
tutorial/ui
16. Packaging Programs in JAR Files
tutorial/deployment/jar
17. Java Web Start
tutorial/deployment/webstart
18. Applets
tutorial/deployment/applet
We welcome feedback on this edition. Please use the Tutorial feedback form: http://developers.sun.com/contact/tutorial_feedback.jsp
xxiii
xxiv
PREFACE
Acknowledgments Many Internet readers have helped us maintain and improve the quality of the tutorial by sending us email and cheerfully pointing out typos, broken links, and areas of the tutorial that caused confusion or could benefit from rewriting. Many current and former members of the Java Software engineering and documentation teams have given us counsel, answered our many questions, reviewed our material, and even made contributions to it. The list is long, but we would particularly like to note the contributions of Eric Armstrong, David Bristor, Martin Buchholz, Mandy Chung, Iris Garcia Clark, Margarita Fischer, Amy Fowler, Andy Herrick, Shannon Hickey, David Holmes, Jim Holmlund, Patrick Keegan, Peter Korn, Masayoshi Okutsu, Scott Seligman, Xueming Shen, Sundar Sivasubramanian, Pete Soper, Scott Violet, and Kathy Walrath. We are also grateful for the talented writers and programmers at Sun who have contributed to the online tutorial as guest authors. We want to thank our former colleague, Joshua Bloch, the original author of the Collections chapter who made the time to provide us with updated information. Thanks also to our external reviewers and longtime supporters, Doug Lea and Brian Goetz. Debra Scott, our manager, gave us encouragement and the support necessary to do our work — and bring it in on time. Our program managers, Mary Lautner and Ian Hardie, tracked schedules, ran interference, and provided comic relief. Illustrators Michael Quillman and Dwayne Wolff created the professional graphics, quickly and efficiently. We also thank the members of the SQE team who have provided valuable feedback. Finally, thanks to the managers in Java SE for allowing their engineers and illustrators time to devote to this effort, and particularly: Uday Dhanikonda, Frances Ho, James Hsieh, Janet Koenig, and Keith Yarwood.
About the Authors Sharon Zakhour, the Tutorial team lead, has worked at Sun as a senior technical writer for seven years. She contributed to The JFC Swing Tutorial, Second Edition, and has worked with the Swing and AWT teams for several years. She graduated from UC Berkeley with a B.A. in Computer Science and has worked as a programmer, developer support engineer, and technical writer for more than twenty years. Scott Hommel is a technical writer on staff at Sun Microsystems, where he documents the Java Platform, Standard Edition. Since 1999, he has contributed to every major
PREFACE
release of the JDK, mostly in the form of API spec clarifications and core release documentation. He currently works from home in the green mountains of Killington, Vermont. Jacob Royal has a master’s degree in IT and an MBA in Information Systems. He has authored administrator’s guides, API references, programmer’s guides and has identified new tools and developed code and writing standards for various companies including Lucent Technologies and Autodesk. He also contributes to the JSR APT specification and the Java deployment guides at Sun. Isaac Rabinovitch is a freelance technical writer. He has authored user’s manuals, programmer’s guides, administrator’s manuals, API references, release notes, and support documentation at Sun, Borland, SGI, and many other companies. He is fond of technical trivia, and has been playing with computers for longer than he cares to think about. Thomas Risser was educated in physics at Harvard (B.A.) and the University of California at Berkeley (Ph.D.). He has been a technical writer in the computer industry for fifteen years. Mark Hoeber is a former senior technical writer at Sun Microsystems. He has worked as a technical writer for twelve years, focusing on documentation for software developers and system administrators. In addition, Mark has worked on implementing content management systems for technical writing teams.
xxv
This page intentionally left blank
1 Getting Started
The Java Technology Phenomenon Talk about Java technology seems to be everywhere, but what exactly is it? The following sections explain how Java technology is both a programming language and a platform, and provide an overview of what this technology can do for you.
About the Java Technology Java technology is both a programming language and a platform.
The Java Programming Language The Java programming language is a high-level language that can be characterized by all of the following buzzwords: • Simple • Architecture neutral • Object oriented • Portable • Distributed • High performance
1
2
CHAPTER 1 GETTING STARTED
• Multithreaded • Robust • Dynamic • Secure Each of the preceding buzzwords is explained in The Java Language Environment,1 a white paper written by James Gosling and Henry McGilton. In the Java programming language, all source code is first written in plain text files ending with the .java extension. Those source files are then compiled into .class files by the javac compiler. A .class file does not contain code that is native to your processor; it instead contains bytecodes—the machine language of the Java Virtual Machine (Java VM).2 The java launcher tool then runs your application with an instance of the Java Virtual Machine (Figure 1.1).
Java 0100101... VM
Compiler MyProgram.java
MyProgram.class My Program
Figure 1.1 Compiling and running an application.
Because the Java VM is available on many different operating systems, the same .class files are capable of running on Microsoft Windows, the Solaris Operating System (Solaris OS), Linux, or Mac OS. Some virtual machines, such as the Java HotSpot virtual machine,3 perform additional steps at runtime to give your application a performance boost. This includes various tasks such as finding performance bottlenecks and recompiling (to native code) frequently used sections of code (Figure 1.2).
1. http://java.sun.com/docs/white/langenv/ 2. The terms “Java Virtual Machine” and “JVM” mean a Virtual Machine for the Java platform. 3. http://java.sun.com/javase/technology/hotspot.jsp
3
THE JAVA TECHNOLOGY PHENOMENON
Source Code class HelloWorldApp { public static void main(String[] args) { System.out.println(”Hello World!”); } HelloWorldApp.java
Compiler Java VM
Win32
Java VM
Solaris OS/Linux
Java VM
Mac OS
Figure 1.2 Through the Java VM, the same application is capable of running on multiple platforms.
The Java Platform A platform is the hardware or software environment in which a program runs. We’ve already mentioned some of the most popular platforms like Microsoft Windows, Linux, Solaris OS, and Mac OS. Most platforms can be described as a combination of the operating system and underlying hardware. The Java platform differs from most other platforms in that it’s a software-only platform that runs on top of other hardware-based platforms. The Java platform has two components: • The Java Virtual Machine • The Java Application Programming Interface (API) You’ve already been introduced to the Java Virtual Machine; it’s the base for the Java platform and is ported onto various hardware-based platforms (Figure 1.3). The API is a large collection of ready-made software components that provide many useful capabilities. It is grouped into libraries of related classes and interfaces; these libraries are known as packages. The next section highlights some of the functionality provided by the API.
4
CHAPTER 1 GETTING STARTED
MyProgram.java API Java Virtual Machine
}
Java platform
Hardware-Based Platform
Figure 1.3 The API and Java Virtual Machine insulate the program from the underlying hardware.
As a platform-independent environment, the Java platform can be a bit slower than native code. However, advances in compiler and virtual machine technologies are bringing performance close to that of native code without threatening portability.
What Can Java Technology Do? The general-purpose, high-level Java programming language is a powerful software platform. Every full implementation of the Java platform gives you the following features: Development Tools The development tools provide everything you’ll need for compiling, running, monitoring, debugging, and documenting your applications. As a new developer, the main tools you’ll be using are the javac compiler, the java launcher, and the javadoc documentation tool. Application Programming Interface (API) The API provides the core functionality of the Java programming language. It offers a wide array of useful classes ready for use in your own applications. The core API is very large; to get an overview of what it contains, consult the Java SE Development Kit 6 (JDK 6) documentation.4 Deployment Technologies The JDK software provides standard mechanisms such as the Java Web Start software and Java Plug-In software for deploying your applications to end users. User Interface Toolkits The Swing and Java 2D toolkits make it possible to create sophisticated Graphical User Interfaces (GUIs).
4. docs/index.html
THE JAVA TECHNOLOGY PHENOMENON
Integration Libraries Integration libraries such as the Java IDL API, JDBC API, Java Naming and Directory Interface (“J.N.D.I.”) API, Java RMI, and Java Remote Method Invocation over Internet Inter-ORB Protocol Technology (Java RMI-IIOP Technology) enable database access and manipulation of remote objects.
How Will Java Technology Change My Life? We can’t promise you fame, fortune, or even a job if you learn the Java programming language. Still, it is likely to make your programs better and requires less effort than other languages. We believe that Java technology will help you do the following: Get started quickly Although the Java programming language is a powerful objectoriented language, it’s easy to learn, especially for programmers already familiar with C or C++. Write less code Comparisons of program metrics (class counts, method counts, and so on) suggest that a program written in the Java programming language can be four times smaller than the same program written in C++. Write better code The Java programming language encourages good coding practices, and automatic garbage collection helps you avoid memory leaks. Its object orientation, its JavaBeans component architecture, and its wide-ranging, easily extendible API let you reuse existing, tested code and introduce fewer bugs. Develop programs more quickly The Java programming language is simpler than C++, and as such, your development time could be up to twice as fast when writing in it. Your programs will also require fewer lines of code. Avoid platform dependencies You can keep your program portable by avoiding the use of libraries written in other languages. Write once, run anywhere Because applications written in the Java programming language are compiled into machine-independent bytecodes, they run consistently on any Java platform. Distribute software more easily With Java Web Start software, users will be able to launch your applications with a single click of the mouse. An automatic version check at startup ensures that users are always up to date with the latest version of your software. If an update is available, the Java Web Start software will automatically update their installation.
5
6
CHAPTER 1 GETTING STARTED
The "Hello World!" Application The following sections provide detailed instructions for compiling and running a simple “Hello World!” application. The first section provides information on getting started with the NetBeans IDE, an integrated development environment that greatly simplifies the software development process. The remaining sections provide platform-specific instructions for getting started without an integrated development environment.
"Hello World!" for the NetBeans IDE It’s time to write your first application! These detailed instructions are for users of the NetBeans IDE. The NetBeans IDE runs on the Java platform, which means that you can use it with any operating system for which there is a JDK 6 available. These operating systems include Microsoft Windows, Solaris OS, Linux, and Mac OS X. If you prefer to follow the tutorial without using an IDE, see (depending on your platform) “Hello World!” for Microsoft Windows (page 14) or “Hello World!” for Solaris OS and Linux (page 19) to get started.
A Checklist To write your first program, you’ll need: 1. The Java SE Development Kit 6 (JDK 6) 2. The NetBeans IDE You can download a bundle of the JDK and NetBeans IDE.5 Bundle installers are available for the Microsoft Windows, Solaris OS, and Linux operating systems. You can also download and install the JDK and the IDE separately. Separate downloads of the JDK are available at: http://java.sun.com/javase/6/download.jsp
(Make sure you download the JDK, not the JRE.) Separate downloads of the NetBeans IDE are available at: http://www.netbeans.org/downloads/
5. http://java.sun.com/javase/6/download.jsp
THE "HELLO WORLD!" APPLICATION
Note: The screen captures shown in this section reflect NetBeans IDE 5.0 running on JDK 6. At the time of this writing, 5.0 was the most current IDE version number. By the time you read this a newer IDE version may be available, but the workflow demonstrated here should remain the same.
Creating Your First Application Your first application, HelloWorldApp, will simply display the greeting “Hello World!”. To create this program, you will: • Create an IDE project. When you create an IDE project, you create an environment in which to build and run your applications. Using IDE projects eliminates configuration issues normally associated with the javac compiler and java launcher tools. You can build or run your application by choosing a single menu item within the IDE. • Add code to the generated source file. A source file contains code, written in the Java programming language, that you and other programmers can understand. As part of creating an IDE project, a skeleton source file will be automatically generated. You will then modify the source file to add the “Hello World!” message. • Compile the source file into a .class file. The IDE invokes the Java programming language compiler (javac), which takes your source file and translates its text into instructions that the Java virtual machine can understand. The instructions contained within this file are known as bytecodes. • Run the program. The IDE invokes the Java application launcher tool (java), which uses the Java virtual machine to run your application. Create an IDE Project To create an IDE project: 1. Launch the NetBeans IDE. • On Microsoft Windows systems, you can use the NetBeans IDE item in the Start menu. • On Solaris OS and Linux systems, you execute the IDE launcher script by navigating to the IDE’s bin directory and typing ./netbeans. • On Mac OS X systems, click the NetBeans IDE application icon. 2. In the NetBeans IDE, choose File | New Project (Figure 1.4).
7
8
CHAPTER 1 GETTING STARTED
Figure 1.4 NetBeans IDE with the File | New Project menu item selected.
3. In the New Project wizard, expand the General category and select Java Application (Figure 1.5).
Figure 1.5 NetBeans IDE, New Project wizard, Choose Project page.
4. In the Name and Location page of the wizard, do the following (Figure 1.6): • In the Project Name field, type Hello World App. • In the Create Main Class field, type helloworldapp.HelloWorldApp. • Leave the Set as Main Project checkbox selected. 5. Click Finish.
THE "HELLO WORLD!" APPLICATION
Figure 1.6 NetBeans IDE, New Project wizard, Name and Location page.
The project is created and opened in the IDE. You should see the following components: • The Projects window, which contains a tree view of the components of the project, including source files, libraries that your code depends on, and so on. • The Source Editor window with a file called HelloWorldApp open. • The Navigator window, which you can use to quickly navigate between elements within the selected class (Figure 1.7). Add Code to the Generated Source File Because you have left the Create Main Class checkbox selected in the New Project wizard, the IDE has created a skeleton class for you. You can add the “Hello World!” message to the skeleton code by replacing the line: // TODO code application logic here
with the line: System.out.println("Hello World!"); // Display the string.
9
10
CHAPTER 1 GETTING STARTED
Figure 1.7 NetBeans IDE with the HelloWorldApp project open.
Optionally, replace these four lines of generated code /** * * @author */
with these lines: /** * The HelloWorldApp class implements an application that * simply prints "Hello World!" to standard output. */
These four lines are a code comment and do not affect how the program runs. Later sections of this tutorial explain the use and format of code comments.
THE "HELLO WORLD!" APPLICATION
Be Careful When You Type: Type all code, commands, and file names exactly as shown. Both the compiler (javac) and launcher (java) are case-sensitive, so you must capitalize consistently. In other words, HelloWorldApp is not equivalent to helloworldapp.
Save the change by choosing File | Save. The file should look something like the following: /* * HelloWorldApp.java * * Created on February 5, 2006, 6:43 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package helloworldapp; /** * The HelloWorldApp class implements an application that * simply prints "Hello World!" to standard output. */ public class HelloWorldApp { /** Creates a new instance of HelloWorldApp */ public HelloWorldApp() { } /** * @param args the command line arguments */ public static void main(String[] args) { System.out.println("Hello World!"); // Display the string. } }
Compile the Source File into a .class File To compile your source file, choose Build | Build Main Project from the IDE’s main menu. The Output window opens and displays output similar to what you see in Figure 1.8.
11
12
CHAPTER 1 GETTING STARTED
Figure 1.8 Output window showing results of building the HelloWorld project.
If the build output concludes with the statement BUILD SUCCESSFUL, congratulations! You have successfully compiled your program! If the build output concludes with the statement BUILD FAILED, you probably have a syntax error in your code. Errors are reported in the Output window as hyper-linked text. You double-click such a hyper-link to navigate to the source of an error. You can then fix the error and once again choose Build | Build Main Project. When you build the project, the bytecode file HelloWorldApp.class is generated. You can see where the new file is generated by opening the Files window and expanding the Hello World App/build/classes/helloworldapp node as shown in Figure 1.9.
Figure 1.9 Files window, showing the generated .class file.
Now that you have built the project, you can run your program. Run the Program From the IDE’s menu bar, choose Run | Run Main Project. Figure 1.10 shows what you should now see.
THE "HELLO WORLD!" APPLICATION
Figure 1.10 The program prints “Hello World!” to the Output window (along with other output from the build script).
Congratulations! Your program works!
Continuing the Tutorial with the NetBeans IDE The section “A Closer Look at the “Hello World!” Application” on page 24 will explain the code in this simple application. Although the rest of the tutorial does not give specific instructions about using the NetBeans IDE, you can easily use the IDE to write and run the sample code. The following are some tips on using the IDE and explanations of some IDE behavior that you are likely to see: • Once you have created a project in the IDE, you can add files to the project using the New File wizard. Choose File | New File, and then select a template in the wizard, such as the Empty Java File template. • You can compile and run an individual file (as opposed to a whole project) using the IDE’s Compile File (F9) and Run File (Shift-F6) commands. If you use the Run Main Project command, the IDE will run the file that the IDE associates as the main class of the main project. Therefore, if you create an additional class in your HelloWorldApp project and then try to run that file with the Run Main Project command, the IDE will run the HelloWorldApp file instead. • You might want to create separate IDE projects for sample applications that include more than one source file. • As you are typing in the IDE, a code completion box might periodically appear. You can either ignore the code completion box and keep typing, or you can select one of the suggested expressions. If you would prefer not to have the code completion box automatically appear, you can turn off the feature. Choose Tools | Options, click the Editor tab, and clear the Auto Popup Completion Window checkbox. • If you try to rename the node for a source file in the Projects window, the IDE prompts you with the Rename dialog box to lead you through the options of renaming the class and the updating of code that refers to that class. Click Next to display the Refactoring window, which contains a tree view of changes to be made. Then click Do Refactoring to apply the changes. This sequence of clicks might seem
13
14
CHAPTER 1 GETTING STARTED
unnecessary if you have just a single class in your project, but it is very useful when your changes affect other parts of your code in larger projects. • For a more thorough guide to the features of the NetBeans IDE, see the NetBeans IDE Docs and Support page6 or explore the documentation available from the IDE’s Help menu.
"Hello World!" for Microsoft Windows It’s time to write your first application! The following instructions are for users of Windows XP Professional, Windows XP Home, Windows Server 2003, Windows 2000 Professional, and Windows Vista. Instructions for Solaris OS and Linux are in the “Hello World!” for Solaris OS and Linux section (page 19).
A Checklist To write your first program, you’ll need: 1. The Java SE Development Kit 6 (JDK 6) You can download the Windows version now.7 (Make sure you download the JDK, not the JRE.) Consult the installation instructions.8 2. A text editor In this example, we’ll use Notepad, a simple editor included with the Windows platforms. You can easily adapt these instructions if you use a different text editor. These two items are all you’ll need to write your first application.
Creating Your First Application Your first application, HelloWorldApp, will simply display the greeting “Hello World!”. To create this program, you will: • Create a source file. A source file contains code, written in the Java programming language, that you and other programmers can understand. You can use any text editor to create and edit source files. • Compile the source file into a .class file. The Java programming language compiler (javac) takes your source file and translates its text into instructions that the Java virtual machine can understand. The instructions contained within this file are known as bytecodes. 6. http://www.netbeans.org/kb/ 7. http://java.sun.com/javase/6/download.jsp 8. http://java.sun.com/javase/6/webnotes/install/
THE "HELLO WORLD!" APPLICATION
• Run the program. The Java application launcher tool (java) uses the Java virtual machine to run your application. Create a Source File To create a source file, you have two options: • You can save the file HelloWorldApp.java9 on your computer and avoid a lot of typing. Then, you can go straight to the Compile the Source File into a .class File section (page 16). • Or, you can use the following (longer) instructions. First, start your editor. You can launch the Notepad editor from the Start menu by selecting Programs > Accessories > Notepad. In a new document, type in the following code: /** * The HelloWorldApp class implements an application that * simply prints "Hello World!" to standard output. */ class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); // Display the string. } }
Be Careful When You Type: Type all code, commands, and file names exactly as shown. Both the compiler (javac) and launcher (java) are case-sensitive, so you must capitalize consistently. In other words, HelloWorldApp is not equivalent to helloworldapp.
Save the code in a file with the name HelloWorldApp.java. To do this in Notepad, first choose the File > Save As menu item. Then, in the Save As dialog box: 1. Using the Save in combo box, specify the folder (directory) where you’ll save your file. In this example, the directory is java on the C drive. 2. In the File name text field, type "HelloWorldApp.java", including the quotation marks. 3. From the Save as type combo box, choose Text Documents (*.txt). 4. In the Encoding combo box, leave the encoding as ANSI.
9. tutorial/getStarted/application/examples/HelloWorldApp.java
15
16
CHAPTER 1 GETTING STARTED
When you’re finished, the dialog box should look like Figure 1.11.
Figure 1.11 The Save As dialog just before you click Save.
Now click Save, and exit Notepad. Compile the Source File into a .class File Bring up a shell, or “command,” window. You can do this from the Start menu by choosing Command Prompt (Windows XP), or by choosing Run . . . and then entering cmd. The shell window should look similar to Figure 1.12. The prompt shows your current directory. When you bring up the prompt, your current directory is usually your home directory for Windows XP (as shown in Figure 1.12).
THE "HELLO WORLD!" APPLICATION
Figure 1.12 A shell window.
To compile your source file, change your current directory to the directory where your file is located. For example, if your source directory is java on the C drive, type the following command at the prompt and press Enter: cd C:\java
Now the prompt should change to C:\java>. Note: To change to a directory on a different drive, you must type an extra command: the name of the drive. For example, to change to the java directory on the D drive, you must enter D:, as shown in Figure 1.13.
Figure 1.13 Changing directory on an alternate drive.
If you enter dir at the prompt, you should see your source file, as Figure 1.14 shows.
17
18
CHAPTER 1 GETTING STARTED
Figure 1.14 Directory listing showing the .java source file.
Now you are ready to compile. At the prompt, type the following command and press Enter. javac HelloWorldApp.java
The compiler has generated a bytecode file, HelloWorldApp.class. At the prompt, type dir to see the new file that was generated, as shown in Figure 1.15.
Figure 1.15 Directory listing showing the generated .class file.
Now that you have a .class file, you can run your program. Run the Program In the same directory, enter the following command at the prompt: java HelloWorldApp
THE "HELLO WORLD!" APPLICATION
Figure 1.16 shows what you should now see.
Figure 1.16 The program prints “Hello World!” to the screen.
Congratulations! Your program works!
"Hello World!" for Solaris OS and Linux It’s time to write your first application! These detailed instructions are for users of Solaris OS and Linux. Instructions for Microsoft Windows are in the “Hello World!” for Microsoft Windows section (page 14).
A Checklist To write your first program, you’ll need: 1. The Java SE Development Kit 6 (JDK 6) You can download the Solaris OS or Linux version now.10 (Make sure you download the JDK, not the JRE.) Consult the installation instructions.11 2. A text editor In this example, we’ll use Pico, an editor available for many UNIX-based platforms. You can easily adapt these instructions if you use a different text editor, such as vi or emacs. These two items are all you’ll need to write your first application.
10. http://java.sun.com/javase/6/download.jsp 11. http://java.sun.com/javase/6/webnotes/install/
19
20
CHAPTER 1 GETTING STARTED
Creating Your First Application Your first application, HelloWorldApp, will simply display the greeting “Hello world!”. To create this program, you will: • Create a source file. A source file contains code, written in the Java programming language, that you and other programmers can understand. You can use any text editor to create and edit source files. • Compile the source file into a .class file. The Java programming language compiler (javac) takes your source file and translates its text into instructions that the Java virtual machine can understand. The instructions contained within this .class file are known as bytecodes. • Run the program. The Java application launcher tool (java) uses the Java virtual machine to run your application. Create a Source File To create a source file, you have two options: • You can save the file HelloWorldApp.java12 on your computer and avoid a lot of typing. Then, you can go straight to the Compile the Source File into a .class File section (page 22). • Or, you can use the following (longer) instructions. First, open a shell, or “terminal,” window (Figure 1.17).
Figure 1.17 A new terminal window.
12. tutorial/getStarted/application/examples/HelloWorldApp.java
THE "HELLO WORLD!" APPLICATION
When you first bring up the prompt, your current directory will usually be your home directory. You can change your current directory to your home directory at any time by typing cd at the prompt and then pressing Return. The source files you create should be kept in a separate directory. You can create a directory by using the command mkdir. For example, to create the directory java in your home directory, use the following commands: cd mkdir java
To change your current directory to this new directory, you then enter: cd java
Now you can start creating your source file. Start the Pico editor by typing pico at the prompt and pressing Return. If the system responds with the message pico: command not found, then Pico is most likely unavailable. Consult your system administrator for more information, or use another editor. When you start Pico, it’ll display a new, blank buffer. This is the area in which you will type your code. Type the following code into the new buffer: /** * The HelloWorldApp class implements an application that * simply prints "Hello World!" to standard output. */ class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); // Display the string. } }
Be Careful When You Type: Type all code, commands, and file names exactly as shown. Both the compiler (javac) and launcher (java) are case-sensitive, so you must capitalize consistently. In other words, HelloWorldApp is not equivalent to helloworldapp.
Save the code in a file with the name HelloWorldApp.java. In the Pico editor, you do this by typing Ctrl-O and then, at the bottom where you see the prompt File Name to write:, entering the directory in which you wish to create the file, followed by HelloWorldApp.java. For example, if you wish to save
21
22
CHAPTER 1 GETTING STARTED
HelloWorldApp.java in the directory /home/jdoe/java, /home/jdoe/java/HelloWorldApp.java and press Return.
then you type
You can type Ctrl-X to exit Pico. Compile the Source File into a .class File Bring up another shell window. To compile your source file, change your current directory to the directory where your file is located. For example, if your source directory is /home/jdoe/java, type the following command at the prompt and press Return: cd /home/jdoe/java
If you enter pwd at the prompt, you should see the current directory, which in this example has been changed to /home/jdoe/java. If you enter ls at the prompt, you should see your file (Figure 1.18).
Figure 1.18 Results of the ls command, showing the .java source file.
Now are ready to compile the source file. At the prompt, type the following command and press Return. javac HelloWorldApp.java
The compiler has generated a bytecode file, HelloWorldApp.class. At the prompt, type ls to see the new file that was generated: Figure 1.19.
THE "HELLO WORLD!" APPLICATION
Figure 1.19 Results of the ls command, showing the generated .class file.
Now that you have a .class file, you can run your program. Run the Program In the same directory, enter at the prompt: java HelloWorldApp
Figure 1.20 shows what you should now see.
Figure 1.20 The output prints “Hello World!” to the screen.
Congratulations! Your program works!
23
24
CHAPTER 1 GETTING STARTED
A Closer Look at the "Hello World!" Application Now that you’ve seen the “Hello World!” application (and perhaps even compiled and run it), you might be wondering how it works. Here again is its code: /** * The HelloWorldApp class implements an application that * simply prints "Hello World!" to standard output. */ class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); // Display the string. } }
The “Hello World!” application consists of three primary components: source code comments, the HelloWorldApp class definition, and the main method. The following explanation will provide you with a basic understanding of of the code, but the deeper implications will only become apparent after you’ve finished reading the subsequent chapters.
Source Code Comments The following bold text defines the comments of the “Hello World!” application: /** * The HelloWorldApp class implements an application that * simply prints "Hello World!" to standard output. */ class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); // Display the string. } }
Comments are ignored by the compiler but are useful to other programmers. The Java programming language supports three kinds of comments: /* text */
The compiler ignores everything from /* to */.
A CLOSER LOOK AT THE "HELLO WORLD!" APPLICATION
This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */. The javadoc tool uses doc comments when preparing automatically generated documentation. For more information on javadoc, see the Javadoc tool documentation.13
/** documentation */
// text
The compiler ignores everything from // to the end of the line.
The HelloWorldApp Class Definition The following bold text begins the class definition block for the “Hello World!” application: /** * The HelloWorldApp class implements an application that * simply prints "Hello World!" to standard output. */ class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); // Display the string. } }
As shown above, the most basic form of a class definition is: class name { ... }
The keyword class begins the class definition for a class named name, and the code for each class appears between the opening and closing curly braces marked in bold above. Chapter 2 provides an overview of classes in general, and Chapter 4 discusses classes in detail. For now it is enough to know that every application begins with a class definition.
The main Method The following bold text begins the definition of the main method:
13. docs/guide/javadoc/index.html
25
26
CHAPTER 1 GETTING STARTED
/** * The HelloWorldApp class implements an application that * simply prints "Hello World!" to standard output. */ class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); // Display the string. } }
In the Java programming language, every application must contain a main method whose signature is: public static void main(String[] args)
The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above. You can name the argument anything you want, but most programmers choose “args” or “argv.” The main method is similar to the main function in C and C++; it’s the entry point for your application and will subsequently invoke all the other methods required by your program. The main method accepts a single argument: an array of elements of type String. public static void main(String[] args)
This array is the mechanism through which the runtime system passes information to your application. Each string in the array is called a command-line argument. Command-line arguments let users affect the operation of the application without recompiling it. For example, a sorting program might allow the user to specify that the data be sorted in descending order with this command-line argument: -descending
The “Hello World!” application ignores its command-line arguments, but you should be aware of the fact that such arguments do exist. Finally, the line: System.out.println("Hello World!");
uses the System class from the API to print the “Hello World!” message to standard output.
COMMON PROBLEMS (AND THEIR SOLUTIONS)
Common Problems (and Their Solutions) Compiler Problems Common Error Messages on Microsoft Windows Systems 'javac' is not recognized as an internal or external command, operable program or batch file
If you receive this error, Windows cannot find the compiler (javac). Here’s one way to tell Windows where to find javac. Suppose you installed the JDK in C:\jdk6. At the prompt you would type the following command and press Enter: C:\jdk6\bin\javac HelloWorldApp.java
If you choose this option, you’ll have to precede your javac and java commands with C:\jdk6\bin\ each time you compile or run a program. To avoid this extra typing, consult the Update the PATH variable section14 in the JDK 6 installation instructions.
Common Error Messages on UNIX Systems javac: Command not found
If you receive this error, UNIX cannot find the compiler, javac. Here’s one way to tell UNIX where to find javac. Suppose you installed the JDK in /usr/local/jdk6. At the prompt you would type the following command and press Return: /usr/local/jdk6/javac HelloWorldApp.java
Note: If you choose this option, each time you compile or run a program, you’ll have to precede your javac and java commands with /usr/local/jdk6/. To avoid this extra typing, you could add this information to your PATH variable. The steps for doing so will vary depending on which shell you are currently running.
Syntax Errors (All Platforms) If you mistype part of a program, the compiler may issue a syntax error. The message usually displays the type of the error, the line number where the error was detected, the
14. http://java.sun.com/javase/6/webnotes/install/jdk/install-windows.html
27
28
CHAPTER 1 GETTING STARTED
code on that line, and the position of the error within the code. Here’s an error caused by omitting a semicolon (;) at the end of a statement: testing.java:14: ';' expected. System.out.println("Input has " + count + " chars.") ^ 1 error
Sometimes the compiler can’t guess your intent and prints a confusing error message or multiple error messages if the error cascades over several lines. For example, the following code snippet omits a semicolon (;) from the bold line: while (System.in.read() != -1) count++ System.out.println("Input has " + count + " chars.");
When processing this code, the compiler issues two error messages: testing.java:13: Invalid type expression. count++ ^ testing.java:14: Invalid declaration. System.out.println("Input has " + count + " chars."); ^ 2 errors
The compiler issues two error messages because after it processes count++, the compiler’s state indicates that it’s in the middle of an expression. Without the semicolon, the compiler has no way of knowing that the statement is complete. If you see any compiler errors, then your program did not successfully compile and the compiler did not create a .class file. Carefully verify the program, fix any errors that you detect, and try again.
Semantic Errors In addition to verifying that your program is syntactically correct, the compiler checks for other basic correctness. For example, the compiler warns you each time you use a variable that has not been initialized: testing.java:13: Variable count may not have been initialized. count++ ^ testing.java:14: Variable count may not have been initialized. System.out.println("Input has " + count + " chars."); ^ 2 errors
COMMON PROBLEMS (AND THEIR SOLUTIONS)
Again, your program did not successfully compile, and the compiler did not create a .class file. Fix the error and try again.
Runtime Problems Error Messages on Microsoft Windows Systems Exception in HelloWorldApp
thread
"main"
java.lang.NoClassDefFoundError:
If you receive this error, java cannot find your bytecode file, HelloWorldApp.class. One of the places java tries to find your .class file is your current directory. So if your .class file is in C:\java, you should change your current directory to that. To change your directory, type the following command at the prompt and press Enter: cd c:\java
The prompt should change to C:\java>. If you enter dir at the prompt, you should see your .java and .class files. Now enter java HelloWorldApp again. CLASSPATH If you still have problems, you might have to change your CLASSPATH
variable. To see if this is necessary, try clobbering the classpath with the following command: set CLASSPATH=
Now enter java HelloWorldApp again. If the program works now, you’ll have to change your CLASSPATH variable. To set this variable, consult the Update the PATH variable section in the JDK 6 installation instructions. The CLASSPATH variable is set in the same manner.
Error Messages on UNIX Systems Exception in HelloWorldApp
thread
"main"
java.lang.NoClassDefFoundError:
If you receive this error, java cannot find your bytecode file, HelloWorldApp.class. One of the places java tries to find your bytecode file is your current directory. So, for example, if your bytecode file is in /home/jdoe/java, you should change your current directory to that. To change your directory, type the following command at the prompt and press Return: cd /home/jdoe/java
29
30
CHAPTER 1 GETTING STARTED
If you enter pwd at the prompt, you should see /home/jdoe/java. If you enter ls at the prompt, you should see your .java and .class files. Now enter java HelloWorldApp again. If you still have problems, you might have to change your CLASSPATH environment variable. To see if this is necessary, try clobbering the classpath with the following command. unset CLASSPATH
Now enter java HelloWorldApp again. If the program works now, you’ll have to change your CLASSPATH variable in the same manner as the PATH variable. A common error of beginner programmers is to try and run the java launcher on the .class file that was created by the compiler. For example, if you try to run your program with java HelloWorldApp.class instead of java HelloWorldApp, you’ll see this error message: Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorldApp/class
The argument is the name of the class that you want to use, not the filename.
The main Method Is Not Defined The Java Virtual Machine requires that the class you execute with it have a main method at which to begin execution of your application. The A Closer Look at the “Hello World!” Application section (page 24) discusses the main method in detail. If you are missing this method, you’ll see the following error at runtime: Exception in thread "main" java.lang.NoSuchMethodError: main
Questions and Exercises: Getting Started Questions 1. When you compile a program written in the Java programming language, the compiler converts the human-readable source file into platform-independent code that a Java Virtual Machine can understand. What is this platform-independent code called? 2. Which of the following is not a valid comment?
QUESTIONS AND EXERCISES: GETTING STARTED
a. /** comment */ b. /* comment */ c. /* comment d. // comment 3. What is the first thing you should check if at runtime you see the following error? Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorldApp.java
4. The signature for the main method must contain the keywords public and static. Does the order of these two keywords matter? 5. The main method accepts a single parameter. By convention, what is this parameter’s name?
Exercises 1. Change the HelloWorldApp.java program so that it displays Hola Mundo! instead of Hello World!. 2. Here is a slightly modified version of HelloWorldApp: // HelloWorldApp2.java // INTENTIONALLY UNCOMPILABLE! /** * The HelloWorldApp class implements an application that * simply prints "Hello World!" to standard output. */ class HelloWorldApp2 { public static void main(String[] args) { System.out.println("Hello World!); // Display the string. } }
The program has an error. Fix the error so that the program successfully compiles and runs. What was the error?
Answers You can find answers to these Questions and Exercises at: tutorial/getStarted/QandE/answers.html
31
This page intentionally left blank
2 Object-Oriented Programming Concepts IF you’ve never used an object-oriented programming language before, you’ll need to learn a few basic concepts before you can begin writing any code. This chapter will introduce you to objects, classes, inheritance, interfaces, and packages. Each discussion focuses on how these concepts relate to the real world while simultaneously providing an introducion to the syntax of the Java programming language.
What Is an Object? Objects are key to understanding object-oriented technology. Look around right now and you’ll find many examples of real-world objects: your dog, your desk, your television set, your bicycle. Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of objectoriented programming. Take a minute right now to observe the real-world objects that are in your immediate area. For each object that you see, ask yourself two questions: “What possible states can this object be in?” and “What possible behavior can this object perform?” Make sure to write down your observations. As you do, you’ll notice that real-world objects vary in complexity; your desktop lamp may have only two possible states (on and off) and two possible behaviors (turn on, turn off) but your desktop radio might have 33
34
CHAPTER 2 OBJECT-ORIENTED PROGRAMMING CONCEPTS
additional states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). You may also notice that some objects, in turn, will also contain other objects. These real-world observations all translate into the world of object-oriented programming. Software objects (Figure 2.1) are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object’s internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object’s methods is known as data encapsulation—a fundamental principle of object-oriented programming.
Fields (state)
Methods (behavior)
Figure 2.1 A software object.
Consider a bicycle (Figure 2.2). By attributing state (current speed, current pedal cadence, and current gear) and providing methods for changing that state, the object remains in control of how the outside world is allowed to use it. For example, if the bicycle only has 6 gears, a method to change gears could reject any value that is less than 1 or greater than 6. Bundling code into individual software objects provides a number of benefits, including: Modularity The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system. Information-hiding By interacting only with an object’s methods, the details of its internal implementation remain hidden from the outside world.
35
WHAT IS A CLASS?
18 mph Change gears 90 rpm Brake
Change cadence
5th gear
Figure 2.2 A bicycle modeled as a software object.
Code re-use If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code. Pluggability and debugging ease If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.
What Is a Class? In the real world, you’ll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created. The following Bicycle1 class is one possible implementation of a bicycle:
1. tutorial/java/concepts/examples/Bicycle.java
36
CHAPTER 2 OBJECT-ORIENTED PROGRAMMING CONCEPTS
class Bicycle { int cadence = 0; int speed = 0; int gear = 1; void changeCadence(int newValue) { cadence = newValue; } void changeGear(int newValue) { gear = newValue; } void speedUp(int increment) { speed = speed + increment; } void applyBrakes(int decrement) { speed = speed - decrement; } void printStates() { System.out.println("cadence:"+cadence+" speed:"+speed+" gear:"+gear); } }
The syntax of the Java programming language will look new to you, but the design of this class is based on the previous discussion of bicycle objects. The fields cadence, speed, and gear represent the object’s state, and the methods (changeCadence, changeGear, speedUp, etc.) define its interaction with the outside world. You may have noticed that the Bicycle class does not contain a main method. That’s because it’s not a complete application; it’s just the blueprint for bicycles that might be used in an application. The responsibility of creating and using new Bicycle objects belongs to some other class in your application. Here’s a BicycleDemo2 class that creates two separate Bicycle objects and invokes their methods:
2. tutorial/java/concepts/examples/BicycleDemo.java
WHAT IS INHERITANCE?
class BicycleDemo { public static void main(String[] args) { // Create two different Bicycle objects Bicycle bike1 = new Bicycle(); Bicycle bike2 = new Bicycle(); // Invoke methods on those objects bike1.changeCadence(50); bike1.speedUp(10); bike1.changeGear(2); bike1.printStates(); bike2.changeCadence(50); bike2.speedUp(10); bike2.changeGear(2); bike2.changeCadence(40); bike2.speedUp(10); bike2.changeGear(3); bike2.printStates(); } }
The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles: cadence:50 speed:10 gear:2 cadence:40 speed:20 gear:3
What Is Inheritance? Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio. Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses (Figure 2.3).
37
38
CHAPTER 2 OBJECT-ORIENTED PROGRAMMING CONCEPTS
Bicycle
MountainBike
RoadBike
TandemBike
Figure 2.3 A hierarchy of bicycle classes.
The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from: class MountainBike extends Bicycle { // new fields and methods defining a mountain bike // would go here }
This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.
What Is an Interface? As you’ve already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object’s interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the “power” button to turn the television on and off.
WHAT IS A PACKAGE?
In its most common form, an interface is a group of related methods with empty bodies. A bicycle’s behavior, if specified as an interface, might appear as follows: interface Bicycle { void changeCadence(int newValue); void changeGear(int newValue); void speedUp(int increment); void applyBrakes(int decrement); }
To implement this interface, the name of your class would change (to ACMEBicycle, for example), and you’d use the implements keyword in the class declaration: class ACMEBicycle implements Bicycle { // remainder of this class implemented as before }
Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.
What Is a Package? A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another. Because software written in the Java programming language can be composed of hundreds or thousands of individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages. The Java platform provides an enormous class library (a set of packages) suitable for use in your own applications. As you learned in Chapter 1, this library is known as the “Application Programming Interface,” or “API” for short. Its packages represent the tasks most commonly associated with general-purpose programming. For example, a String object contains state and behavior for character strings; a File object allows a programmer to easily create, delete, inspect, compare, or modify a file on the filesystem; a Socket object allows for the creation and use of network sockets; various GUI
39
40
CHAPTER 2 OBJECT-ORIENTED PROGRAMMING CONCEPTS
objects control buttons and checkboxes and anything else related to graphical user interfaces. There are literally thousands of classes to choose from. This allows you, the programmer, to focus on the design of your particular application, rather than the infrastructure required to make it work. The Java Platform API Specification3 contains the complete listing for all packages, interfaces, classes, fields, and methods supplied by the Java Platform 6, Standard Edition. Load the page in your browser and bookmark it. As a programmer, it will become your single most important piece of reference documentation.
Questions and Exercises: Object-Oriented Programming Concepts Questions 1. Real-world objects contain ___ and ___. 2. A software object’s state is stored in ___. 3. A software object’s behavior is exposed through ___. 4. Hiding internal data from the outside world and accessing it only through publicly exposed methods is known as data ___. 5. A blueprint for a software object is called a ___. 6. Common behavior can be defined in a ___ and inherited into a ___ using the ___ keyword. 7. A collection of methods with no implementation is called an ___. 8. A namespace that organizes classes and interfaces by functionality is called a ___. 9. The term API stands for ___?
Exercises 1. Create new classes for each real-world object that you observed at the beginning of this trail. Refer to the Bicycle class if you forget the required syntax. 2. For each new class that you’ve created above, create an interface that defines its behavior, then require your class to implement it. Omit one or two methods and try compiling. What does the error look like?
3. docs/api/index.html
QUESTIONS AND EXERCISES: OBJECT-ORIENTED PROGRAMMING CONCEPTS
Answers You can find answers to these Questions and Exercises at: tutorial/java/concepts/QandE/answers.html
41
This page intentionally left blank
3 Language Basics
Variables As you learned in the previous chapter, an object stores its state in fields. int cadence = 0; int speed = 0; int gear = 1;
The What Is an Object? section (page 33) introduced you to fields, but you probably still have a few questions, such as: What are the rules and conventions for naming a field? Besides int, what other data types are there? Do fields have to be initialized when they are declared? Are fields assigned a default value if they are not explicitly initialized? We’ll explore the answers to such questions in this chapter, but before we do, there are a few technical distinctions you must first become aware of. In the Java programming language, the terms “field” and “variable” are both used; this is a common source of confusion among new developers, since both often seem to refer to the same thing. The Java programming language defines the following kinds of variables: Instance Variables (Non-Static Fields) Technically speaking, objects store their individual state in “non-static fields,” that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another. 43
44
CHAPTER 3 LANGUAGE BASICS
Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int numGears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change. Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0; ). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared—which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class. Parameters You’ve already seen examples of parameters, both in the Bicycle class and in the main method of the “Hello World!” application. Recall that the signature for the main method is public static void main(String[] args). Here, the args variable is the parameter to this method. The important thing to remember is that parameters are always classified as “variables,” not “fields.” This applies to other parameter-accepting constructs as well (such as constructors and exception handlers) that you’ll learn about later in the tutorial. Having said that, the remainder of this tutorial uses the following general guidelines when discussing fields and variables. If we are talking about “fields in general” (excluding local variables and parameters), we may simply say “fields.” If the discussion applies to “all of the above,” we may simply say “variables.” If the context calls for a distinction, we will use specific terms (static field, local variable, etc.) as appropriate. You may also occasionally see the term “member” used as well. A type’s fields, methods, and nested types are collectively called its members.
Naming Every programming language has its own set of rules and conventions for the kinds of names that you’re allowed to use, and the Java programming language is no different. The rules and conventions for naming your variables can be summarized as follows: • Variable names are case sensitive. A variable’s name can be any legal identifier—an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign, “$”, or the underscore character, “_”. The convention, however, is to always begin your variable names with a letter, not “$” or “_”. Additionally, the
VARIABLES
dollar sign character, by convention, is never used at all. You may find some situations were auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it’s technically legal to begin your variable’s name with “_”, this practice is discouraged. White space is not permitted. • Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named cadence, speed, and gear, for example, are much more intuitive than abbreviated versions, such as s, c, and g. Also keep in mind that the name you choose must not be a keyword or reserved word. See Appendix A, “Java Language Keywords” on page 603. • If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention. If your variable stores a constant value, such as static final int NUM_GEARS = 6 , the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.
Primitive Data Types The Java programming language is strongly typed, which means that all variables must first be declared before they can be used. This involves stating the variable’s type and name, as you’ve already seen: int gear = 1;
Doing so tells your program that a field named “gear” exists, holds numerical data, and has an initial value of “1”. A variable’s data type determines the values it may contain, plus the operations that may be performed on it. In addition to int, the Java programming language supports seven other primitive data types. A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java programming language are: byte The byte data type is an 8-bit signed two’s complement integer. It has a minimum value of –128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. You’ll learn about arrays on page 49. They can also be used in place of int, where their limits help to clarify your code; the fact that a variable’s range is limited can serve as a form of documentation.
45
46
CHAPTER 3 LANGUAGE BASICS
short The short data type is a 16-bit signed two’s complement integer. It has a minimum value of –32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters. int
The int data type is a 32-bit signed two’s complement integer. It has a minimum value of –2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else. This data type will most likely be large enough for the numbers your program will use, but if you need a wider range of values, use long instead.
long The long data type is a 64-bit signed two’s complement integer. It has a minimum value of –9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int. float The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification.1 As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead.2 Chapter 8 covers BigDecimal and other useful classes provided by the Java platform. double The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency. boolean The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its “size” isn’t something that’s precisely defined. char The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
1. docs/books/jls/third_edition/html/typesValues.html 2. docs/api/java/math/BigDecimal.html
47
VARIABLES
In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java.lang.String class.3 Enclosing your character string within double quotes will automatically create a new String object; for example, String s = "this is a string"; . String objects are immutable, which means that once created, their values cannot be changed. The String class is not technically a primitive data type, but considering the special support given to it by the language, you’ll probably tend to think of it as such. You’ll learn more about the String class in Chapter 8.
Default Values It’s not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a resonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style. Table 3.1 summarizes the default values for the above data types. Table 3.1 Data Types and Their Default Values Data Type
Default Value (for fields)
byte
0
short
0
int
0
long
0L
float
0.0f
double
0.0d
char String (or any object)
boolean
'\u0000' null false
Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.
3. docs/api/java/lang/String.html
48
CHAPTER 3 LANGUAGE BASICS
Literals You may have noticed that the new keyword isn’t used when initializing a variable of a primitive type. Primitive types are special data types built into the language; they are not objects created from a class. A literal is the source code representation of a fixed value; literals are represented directly in your code without requiring computation. As shown below, it’s possible to assign a literal to a variable of a primitive type: boolean result = true; char capitalC = 'C'; byte b = 100; short s = 10000; int i = 100000;
The integral types (byte, short, int, and long) can be expressed using decimal, octal, or hexadecimal number systems. Decimal is the number system you already use every day; it’s based on 10 digits, numbered 0 through 9. The octal number system is base 8, consisting of the digits 0 through 7. The hexadecimal system is base 16, whose digits are the numbers 0 through 9 and the letters A through F. For general-purpose programming, the decimal system is likely to be the only number system you’ll ever use. However, if you need octal or hexadecimal, the following example shows the correct syntax. The prefix 0 indicates octal, whereas 0x indicates hexadecimal. int decVal = 26; int octVal = 032; int hexVal = 0x1a;
// The number 26, in decimal // The number 26, in octal // The number 26, in hexadecimal
The floating point types (float and double) can also be expressed using E or e (for scientific notation), F or f (32-bit float literal), and D or d (64-bit double literal; this is the default and by convention is omitted). double d1 = 123.4; double d2 = 1.234e2; // same value as d1, // but in scientific notation float f1 = 123.4f;
Literals of types char and String may contain any Unicode (UTF-16) characters. If your editor and file system allow it, you can use such characters directly in your code. If not, you can use a “Unicode escape” such as '\u0108' (capital C with circumflex) or "S\u00ED se\u00F1or" (Sí Señor in Spanish). Always use ‘single quotes’ for char literals and “double quotes” for String literals. Unicode escape sequences may be used elsewhere in a program (such as in field names, for example), not just in char or String literals.
VARIABLES
The Java programming language also supports a few special escape sequences for char and String literals: \b (backspace), \t (tab), \n (line feed), \f (form feed), \r (carriage return), \" (double quote), \' (single quote), and \\ (backslash). There’s also a special null literal that can be used as a value for any reference type. null may be assigned to any variable, except variables of primitive types. There’s little you can do with a null value beyond testing for its presence. Therefore, null is often used in programs as a marker to indicate that some object is unavailable. Finally, there’s also a special kind of literal called a class literal, formed by taking a type name and appending “.class”; for example, String.class. This refers to the object (of type Class) that represents the type itself.
Arrays An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You’ve seen an example of arrays already, in the main method of the “Hello World!” application. This section discusses arrays in greater detail.
Figure 3.1 An array of ten elements.
Each item in an array is called an element, and each element is accessed by its numerical index. As shown in Figure 3.1, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8. The following program, ArrayDemo,4 creates an array of integers, puts some values in it, and prints each value to standard output.
4. tutorial/java/nutsandbolts/examples/ArrayDemo.java
49
50
CHAPTER 3 LANGUAGE BASICS
class ArrayDemo { public static void main(String[] args) { int[] anArray; // declares an array of integers anArray = new int[10]; anArray[0] anArray[1] anArray[2] anArray[3] anArray[4] anArray[5] anArray[6] anArray[7] anArray[8] anArray[9]
= = = = = = = = = =
// allocates memory for 10 integers
100; // initialize first element 200; // initialize second element 300; // etc. 400; 500; 600; 700; 800; 900; 1000;
System.out.println("Element System.out.println("Element System.out.println("Element System.out.println("Element System.out.println("Element System.out.println("Element System.out.println("Element System.out.println("Element System.out.println("Element System.out.println("Element
at at at at at at at at at at
index index index index index index index index index index
0: 1: 2: 3: 4: 5: 6: 7: 8: 9:
" " " " " " " " " "
+ + + + + + + + + +
anArray[0]); anArray[1]); anArray[2]); anArray[3]); anArray[4]); anArray[5]); anArray[6]); anArray[7]); anArray[8]); anArray[9]);
} }
The output from this program is: Element Element Element Element Element Element Element Element Element Element
at at at at at at at at at at
index index index index index index index index index index
0: 1: 2: 3: 4: 5: 6: 7: 8: 9:
100 200 300 400 500 600 700 800 900 1000
In a real-world programming situation, you’d probably use one of the supported looping constructs to iterate through each element of the array, rather than write each line individually as shown above. However, this example clearly illustrates the array syntax. You’ll learn about the various looping constructs (for, while, and do-while) in the Control Flow Statements section (page 69).
VARIABLES
Declaring a Variable to Refer to an Array The above program declares anArray with the following line of code: int[] anArray;
// declares an array of integers
Like declarations for variables of other types, an array declaration has two components: the array’s type and the array’s name. An array’s type is written as type[], where type is the data type of the contained elements; the square brackets are special symbols indicating that this variable holds an array. The size of the array is not part of its type (which is why the brackets are empty). An array’s name can be anything you want, provided that it follows the rules and conventions as previously discussed in the Naming section (page 44). As with variables of other types, the declaration does not actually create an array—it simply tells the compiler that this variable will hold an array of the specified type. Similarly, you can declare arrays of other types: byte[] anArrayOfBytes; short[] anArrayOfShorts; long[] anArrayOfLongs; float[] anArrayOfFloats; double[] anArrayOfDoubles; boolean[] anArrayOfBooleans; char[] anArrayOfChars; String[] anArrayOfStrings;
You can also place the square brackets after the array’s name: float anArrayOfFloats[]; // this form is discouraged
However, convention discourages this form; the brackets identify the array type and should appear with the type designation.
Creating, Initializing, and Accessing an Array One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates an array with enough memory for ten integer elements and assigns the array to the anArray variable. anArray = new int[10];
// create an array of integers
If this statement were missing, the compiler would print an error like the following, and compilation would fail: ArrayDemo.java:4: Variable anArray may not have been initialized.
51
52
CHAPTER 3 LANGUAGE BASICS
The next few lines assign values to each element of the array: anArray[0] = 100; // initialize first element anArray[1] = 200; // initialize second element anArray[2] = 300; // etc.
Each array element is accessed by its numerical index: System.out.println("Element 1 at index 0: " + anArray[0]); System.out.println("Element 2 at index 1: " + anArray[1]); System.out.println("Element 3 at index 2: " + anArray[2]);
Alternatively, you can use the shortcut syntax to create and initialize an array: int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};
Here the length of the array is determined by the number of values provided between { and }. You can also declare an array of arrays (also known as a multidimensional array) by using two or more sets of square brackets, such as String[][] names. Each element, therefore, must be accessed by a corresponding number of index values. In the Java programming language, a multidimensional array is simply an array whose components are themselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the rows are allowed to vary in length, as shown in the following MultiDimArrayDemo5 program: class MultiDimArrayDemo { public static void main(String[] args) { String[][] names = {{"Mr. ", "Mrs. ", "Ms. "}, {"Smith", "Jones"}}; System.out.println(names[0][0] + names[1][0]); // Mr. Smith System.out.println(names[0][2] + names[1][1]); // Ms. Jones } }
The output from this program is: Mr. Smith Ms. Jones
5. tutorial/java/nutsandbolts/examples/MultiDimArrayDemo.java
VARIABLES
Finally, you can use the built-in length property to determine the size of any array. The code System.out.println(anArray.length);
will print the array’s size to standard output.
Copying Arrays The System class has an arraycopy method that you can use to efficiently copy data from one array into another: public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
The two Object arguments specify the array to copy from and the array to copy to. The three int arguments specify the starting position in the source array, the starting position in the destination array, and the number of array elements to copy. The following program, ArrayCopyDemo, declares an array of char elements, spelling the word “decaffeinated.” It uses arraycopy to copy a subsequence of array components into a second array: class ArrayCopyDemo { public static void main(String[] args) { char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' }; char[] copyTo = new char[7]; System.arraycopy(copyFrom, 2, copyTo, 0, 7); System.out.println(new String(copyTo)); } }
The output from this program is: caffein
Summary of Variables The Java programming language uses both “fields” and “variables” as part of its terminology. Instance variables (non-static fields) are unique to each instance of a class. Class variables (static fields) are fields declared with the static modifier; there is exactly one copy of a class variable, regardless of how many times the class has been
53
54
CHAPTER 3 LANGUAGE BASICS
instantiated. Local variables store temporary state inside a method. Parameters are variables that provide extra information to a method; both local variables and parameters are always classified as “variables” (not “fields”). When naming your fields or variables, there are rules and conventions that you should (or must) follow. The eight primitive data types are: byte, short, int, long, float, double, boolean, and char. The java.lang.String class represents character strings. The compiler will assign a reasonable default value for fields of the above types; for local variables, a default value is never assigned. A literal is the source code representation of a fixed value. An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
Questions and Exercises: Variables Questions 1. The term “instance variable” is another name for ___. 2. The term “class variable” is another name for ___. 3. A local variable stores temporary state; it is declared inside a ___. 4. A variable declared within the opening and closing parentheses of a method signature is called a ____. 5. What are the eight primitive data types supported by the Java programming language? 6. Character strings are represented by the class ___. 7. An ___ is a container object that holds a fixed number of values of a single type.
Exercises 1. Create a small program that defines some fields. Try creating some illegal field names and see what kind of error the compiler produces. Use the naming rules and conventions as a guide. 2. In the program you created in Exercise 1, try leaving the fields uninitialized and print out their values. Try the same with a local variable and see what kind of compiler errors you can produce. Becoming familiar with common compiler errors will make it easier to recognize bugs in your code.
OPERATORS
Answers You can find answers to these Questions and Exercises at: tutorial/java/nutsandbolts/QandE/answers_variables.html
Operators Now that you’ve learned how to declare and initialize variables, you probably want to know how to do something with them. Learning the operators of the Java programming language is a good place to start. Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result. As we explore the operators of the Java programming language, it may be helpful for you to know ahead of time which operators have the highest precedence. The operators in Table 3.2 are listed according to precedence order. The closer to the top of the table an operator appears, the higher its precedence. Operators with higher precedence are Table 3.2 Operator Precedence Operators
Precedence
postfix
expr++ expr--
unary
++expr --expr +expr -expr ~ !
multiplicative
* / %
additive
+ -
shift
> >>>
relational
< > = instanceof
equality
== !=
bitwise AND
&
bitwise exclusive OR
^
bitwise inclusive OR
|
logical AND
&&
logical OR
||
ternary
? :
assignment
= += -= *= /= %= &= ^= |= = >>>=
55
56
CHAPTER 3 LANGUAGE BASICS
evaluated before operators with relatively lower precedence. Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left. In general-purpose programming, certain operators tend to appear more frequently than others; for example, the assignment operator “= ” is far more common than the unsigned right shift operator “>>>”. With that in mind, the following discussion focuses first on the operators that you’re most likely to use on a regular basis, and ends focusing on those that are less common. Each discussion is accompanied by sample code that you can compile and run. Studying its output will help enforce what you’ve just learned.
Assignment, Arithmetic, and Unary Operators The Simple Assignment Operator One of the most common operators that you’ll encounter is the simple assignment operator “= ”. You saw this operator in the Bicycle class; it assigns the value on its right to the operand on its left: int cadence = 0; int speed = 0; int gear = 1;
This operator can also be used on objects to assign object references, as discussed in Chapter 8.
The Arithmetic Operators The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There’s a good chance you’ll recognize them by their counterparts in basic mathematics. The only symbol that might look new to you is “%”, which divides one operand by another and returns the remainder as its result. + * / %
additive operator (also used for String concatenation) subtraction operator multiplication operator division operator remainder operator
The following program, ArithmeticDemo,6 tests the arithmetic operators.
6. tutorial/java/nutsandbolts/examples/ArithmeticDemo.java
OPERATORS
class ArithmeticDemo { public static void main (String[] args){ int result = 1 + 2; // result is now 3 System.out.println(result); result = result - 1; // result is now 2 System.out.println(result); result = result * 2; // result is now 4 System.out.println(result); result = result / 2; // result is now 2 System.out.println(result); result = result + 8; // result is now 10 result = result % 7; // result is now 3 System.out.println(result); } }
You can also combine the arithmetic operators with the simple assignment operator to create compound assignments. For example, x+=1; and x=x+1; both increment the value of x by 1. The + operator can also be used for concatenating (joining) two strings together, as shown in the following ConcatDemo7 program: class ConcatDemo { public static void main(String[] args){ String firstString = "This is"; String secondString = " a concatenated string."; String thirdString = firstString+secondString; System.out.println(thirdString); } }
By the end of this program, the variable thirdString contains “This is a concatenated string.”, which gets printed to standard output.
7. tutorial/java/nutsandbolts/examples/ConcatDemo.java
57
58
CHAPTER 3 LANGUAGE BASICS
The Unary Operators The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean. + ++ -!
Unary plus operator; indicates positive value (numbers are positive without this, however) Unary minus operator; negates an expression Increment operator; increments a value by 1 Decrement operator; decrements a value by 1 Logical complement operator; inverts the value of a boolean
The following program, UnaryDemo,8 tests the unary operators: class UnaryDemo { public static void main(String[] args){ int result = +1; // result is now 1 System.out.println(result); result--; // result is now 0 System.out.println(result); result++; // result is now 1 System.out.println(result); result = -result; // result is now -1 System.out.println(result); boolean success = false; System.out.println(success); // false System.out.println(!success); // true } }
The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn’t really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference. The following program, PrePostDemo, illustrates the prefix/postfix unary increment operator:
8. tutorial/java/nutsandbolts/examples/UnaryDemo.java
OPERATORS
class PrePostDemo { public static void main(String[] args){ int i = 3; i++; System.out.println(i); // "4" ++i; System.out.println(i); // "5" System.out.println(++i); // "6" System.out.println(i++); // "6" System.out.println(i); // "7" } }
Equality, Relational, and Conditional Operators The Equality and Relational Operators The equality and relational operators determine if one operator is greater than, less than, equal to, or not equal to another operand. The majority of these operators will probably look familiar to you as well. Keep in mind that you must use “== ”, not “= ”, when testing if two primitive values are equal. == != > >= < value2) System.out.println("value1 > value2"); if(value1 < value2) System.out.println("value1 < value2"); if(value1 >” shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension. The bitwise & operator performs a bitwise AND operation. The bitwise ^ operator performs a bitwise exclusive OR operation. The bitwise | operator performs a bitwise inclusive OR operation. For & and | above, the result has a 1 in each bit position for which both of the operands have a 1. The following program, BitDemo,13 uses the bitwise AND operator to print the number “2” to standard output.
13. tutorial/java/nutsandbolts/examples/BitDemo.java
OPERATORS
class BitDemo { public static void main(String[] args) { int bitmask = 0x000F; int val = 0x2222; System.out.println(val & bitmask); // prints "2" } }
Summary of Operators The following quick reference summarizes the operators supported by the Java programming language. Simple Assignment Operator =
simple assignment operator
Arithmetic Operators + * / %
additive operator (also used for String concatenation) subtraction operator multiplication operator division operator remainder operator
Unary Operators + ++ -!
Unary plus operator; indicates positive value (numbers are positive without this, however) Unary minus operator; negates an expression Increment operator; increments a value by 1 Decrement operator; decrements a value by 1 Logical complement operator; inverts the value of a boolean
Equality and Relational Operators == != > >=
>> & ^ |
unary bitwise complement signed left shift signed right shift unsigned right shift bitwise AND bitwise exclusive OR bitwise inclusive OR
Questions and Exercises: Operators Questions 1. Consider the following code snippet. arrayOfInts[j] > arrayOfInts[j+1]
Which operators does the code contain? 2. Consider the following code snippet. int i = 10; int n = i++%5;
a. What are the values of i and n after the code is executed? b. What are the final values of i and n if instead of using the postfix increment operator (i++) you use the prefix version (++i)? 3. To invert the value of a boolean, which operator would you use? 4. Which operator is used to compare two values, = or == ? 5. Explain the following code sample: result = someCondition ? value1 : value2;
Exercises 1. Change the following program to use compound assignments:
OPERATORS
class ArithmeticDemo { public static void main (String[] args){ int result = 1 + 2; // result is now 3 System.out.println(result); result = result - 1; // result is now 2 System.out.println(result); result = result * 2; // result is now 4 System.out.println(result); result = result / 2; // result is now 2 System.out.println(result); result = result + 8; // result is now 10 result = result % 7; // result is now 3 System.out.println(result); } }
2. In the following program, explain why the value “6” is printed twice in a row: class PrePostDemo { public static void main(String[] args){ int i = 3; i++; System.out.println(i); // "4" ++i; System.out.println(i); // "5" System.out.println(++i); // "6" System.out.println(i++); // "6" System.out.println(i); // "7" } }
Answers You can find answers to these Questions and Exercises at: tutorial/java/nutsandbolts/QandE/questions_expressions.html
65
66
CHAPTER 3 LANGUAGE BASICS
Expressions, Statements, and Blocks Now that you understand variables and operators, it’s time to learn about expressions, statements, and blocks. Operators may used in building expressions, which compute values; expressions are the core components of statements; statements may be grouped into blocks.
Expressions An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value. You’ve already seen examples of expressions, illustrated in bold below: int cadence = 0 ; anArray[0] = 100 ; System.out.println("Element 1 at index 0: " + anArray[0]); int result = 1 + 2 ; // result is now 3 if(value1 == value2 ) System.out.println("value1 == value2" );
The data type of the value returned by an expression depends on the elements used in the expression. The expression cadence = 0 returns an int because the assignment operator returns a value of the same data type as its left-hand operand; in this case, cadence is an int. As you can see from the other expressions, an expression can return other types of values as well, such as boolean or String. The Java programming language allows you to construct compound expressions from various smaller expressions as long as the data type required by one part of the expression matches the data type of the other. Here’s an example of a compound expression: 1 * 2 * 3
In this particular example, the order in which the expression is evaluated is unimportant because the result of multiplication is independent of order; the outcome is always the same, no matter in which order you apply the multiplications. However, this is not true of all expressions. For example, the following expression gives different results, depending on whether you perform the addition or the division operation first: x + y / 100
// ambiguous
You can specify exactly how an expression will be evaluated using balanced parenthesis: ( and ). For example, to make the previous expression unambiguous, you could write the following:
EXPRESSIONS, STATEMENTS, AND BLOCKS
(x + y) / 100
// unambiguous, recommended
If you don’t explicitly indicate the order for the operations to be performed, the order is determined by the precedence assigned to the operators in use within the expression. Operators that have a higher precedence get evaluated first. For example, the division operator has a higher precedence than does the addition operator. Therefore, the following two statements are equivalent: x + y / 100 x + (y / 100)
// unambiguous, recommended
When writing compound expressions, be explicit and indicate with parentheses which operators should be evaluated first. This practice makes code easier to read and to maintain.
Statements Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon (;). • Assignment expressions • Any use of ++ or -• Method invocations • Object creation expressions Such statements are called expression statements. Here are some examples of expression statements. aValue = 8933.234; // assignment statement aValue++; // increment statement System.out.println("Hello World!"); // method invocation // statement Bicycle myBike = new Bicycle(); // object creation // statement
In addition to expression statements, there are two other kinds of statements: declaration statements and control flow statements. A declaration statement declares a variable. You’ve seen many examples of declaration statements already: double aValue = 8933.234; // declaration statement
67
68
CHAPTER 3 LANGUAGE BASICS
Finally, control flow statements regulate the order in which statements get executed. You’ll learn about control flow statements in the Control Flow Statements section (page 69).
Blocks A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed. The following example, BlockDemo,14 illustrates the use of blocks: class BlockDemo { public static void main(String[] args) { boolean condition = true; if (condition) { // begin block 1 System.out.println("Condition is true."); } // end block one else { // begin block 2 System.out.println("Condition is false."); } // end block 2 } }
Questions and Exercises: Expressions, Statements, and Blocks Questions 1. Operators may used in building ___, which compute values. 2. Expressions are the core components of ___. 3. Statements may be grouped into ___. 4. The following code snippet is an example of a ___ expression. 1 * 2 * 3
5. Statements are roughly equivalent to sentences in natural languages, but instead of ending with a period, a statement ends with a ___. 6. A block is a group of zero or more statements between balanced ___ and can be used anywhere a single statement is allowed.
14. tutorial/java/nutsandbolts/examples/BlockDemo.java
CONTROL FLOW STATEMENTS
Exercises Identify the following kinds of expression statements: • aValue = 8933.234; • aValue++; • System.out.println("Hello World!"); • Bicycle myBike = new Bicycle();
Answers You can find answers to these Questions and Exercises at: tutorial/java/nutsandbolts/QandE/answers_expressions.html
Control Flow Statements The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code. This section describes the decisionmaking statements (if-then, if-then-else, switch), the looping statements (for, while, do-while), and the branching statements (break, continue, return) supported by the Java programming language.
The if-then and if-then-else Statements The if-then Statement The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true. For example, the Bicycle class could allow the brakes to decrease the bicycle’s speed only if the bicycle is already in motion. One possible implementation of the applyBrakes method could be as follows:
69
70
CHAPTER 3 LANGUAGE BASICS
void applyBrakes(){ if (isMoving){ // the "if" clause: bicycle must moving currentSpeed--; // the "then" clause: // decrease current speed } }
If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the end of the if-then statement. In addition, the opening and closing braces are optional, provided that the “then” clause contains only one statement: void applyBrakes(){ if (isMoving) currentSpeed--; // same as above, // but without braces }
Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code more brittle. If a second statement is later added to the “then” clause, a common mistake would be forgetting to add the newly required braces. The compiler cannot catch this sort of error; you’ll just get the wrong results.
The if-then-else Statement The if-then-else statement provides a secondary path of execution when an “if” clause evaluates to false. You could use an if-then-else statement in the applyBrakes method to take some action if the brakes are applied when the bicycle is not in motion. In this case, the action is to simply print an error message stating that the bicycle has already stopped. void applyBrakes(){ if (isMoving) { currentSpeed--; } else { System.err.println("The bicycle has already stopped!"); } }
The following program, IfElseDemo,15 assigns a grade based on the value of a test score: an A for a score of 90% or above, a B for a score of 80% or above, and so on.
15. tutorial/java/nutsandbolts/examples/IfElseDemo.java
CONTROL FLOW STATEMENTS
class IfElseDemo { public static void main(String[] args) { int testscore = 76; char grade; if (testscore >= 90) { grade = 'A'; } else if (testscore >= 80) grade = 'B'; } else if (testscore >= 70) grade = 'C'; } else if (testscore >= 60) grade = 'D'; } else { grade = 'F'; } System.out.println("Grade =
{ { {
" + grade);
} }
The output from the program is: Grade = C
You may have noticed that the value of testscore can satisfy more than one expression in the compound statement: 76 >= 70 and 76 >= 60 . However, once a condition is satisfied, the appropriate statements are executed (grade = 'C';) and the remaining conditions are not evaluated.
The switch Statement Unlike if-then and if-then-else, the switch statement allows for any number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types discussed in the Enum Types section (page 128) and a few special classes that “wrap” certain primitive types: Character,16 Byte,17 Short,18 and Integer19 discussed in Chapter 8.
16. docs/api/java/lang/Character.html 17. docs/api/java/lang/Byte.html 18. docs/api/java/lang/Short.html 19. docs/api/java/lang/Integer.html
71
72
CHAPTER 3 LANGUAGE BASICS
The following program, SwitchDemo,20 declares an int named month whose value represents a month out of the year. The program displays the name of the month, based on the value of month, using the switch statement. class SwitchDemo { public static void main(String[] args) { int month = 8; switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; default: System.out.println("Invalid month.");break; } } }
In this case, “August” is printed to standard output. The body of a switch statement is known as a switch block. Any statement immediately contained by the switch block may be labeled with one or more case or default labels. The switch statement evaluates its expression and executes the appropriate case. Of course, you could also implement the same thing with if-then-else statements: int month = 8; if (month == 1) { System.out.println("January"); } else if (month == 2) { System.out.println("February"); } ... // and so on
Deciding whether to use if-then-else statements or a switch statement is sometimes a judgment call. You can decide which one to use based on readability and other factors. An if-then-else statement can be used to make decisions based on ranges of values
20. tutorial/java/nutsandbolts/examples/SwitchDemo.java
CONTROL FLOW STATEMENTS
or conditions, whereas a switch statement can make decisions based only on a single integer or enumerated value. Another point of interest is the break statement after each case. Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, case statements fall through; that is, without an explicit break, control will flow sequentially through subsequent case statements. The following program, SwitchDemo2,21 illustrates why it might be useful to have case statements fall through: class SwitchDemo2 { public static void main(String[] args) { int month = 2; int year = 2000; int numDays = 0; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numDays = 31; break; case 4: case 6: case 9: case 11: numDays = 30; break; case 2: if ( ((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0) ) numDays = 29; else numDays = 28; break; default: System.out.println("Invalid month."); break; } System.out.println("Number of Days = " + numDays); } }
21. tutorial/java/nutsandbolts/examples/SwitchDemo2.java
73
74
CHAPTER 3 LANGUAGE BASICS
This is the output from the program: Number of Days = 29
Technically, the final break is not required because flow would fall out of the switch statement anyway. However, we recommend using a break so that modifying the code is easier and less error-prone. The default section handles all values that aren’t explicitly handled by one of the case sections.
The while and do-while Statements The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as: while (expression) { statement(s) }
The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false. Using the while statement to print the values from 1 through 10 can be accomplished as in the following WhileDemo22 program: class WhileDemo { public static void main(String[] args){ int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } } }
You can implement an infinite loop using the while statement as follows: while (true){ // your code goes here }
The Java programming language also provides a do-while statement, which can be expressed as follows:
22. tutorial/java/nutsandbolts/examples/WhileDemo.java
CONTROL FLOW STATEMENTS
do { statement(s) } while (expression);
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once, as shown in the following DoWhileDemo23 program: class DoWhileDemo { public static void main(String[] args){ int count = 1; do { System.out.println("Count is: " + count); count++; } while (count