Σχόλια 0

Το κείμενο του εγγράφου

Get the Java skills and know-how that you’ll needto learn and write successful Android appsLearnJava for AndroidDevelopmentJeff “JavaJeff” FriesenThis book was purchased by harshamv@variable3.comLearn Java for AndroidDevelopment

About the AuthorJeff “JavaJeff” Friesen has been actively involved with Java since the late1990s. Jeff has worked with Java in various companies, including ahealthcare-oriented consulting firm, where he created his own Java/C++software for working with smart cards. Jeff has written about Java innumerous articles for JavaWorld (www.javaworld.com), informIT(www.informit.com), and java.net (http://java.net), and has authoredseveral books on Java, including Beginning Java SE 6 Platform: From Noviceto Professional (Apress, 2007; ISBN: 159059830X), which focuses exclusivelyon Java version 6’s new and improved features. Jeff has also taught Java inuniversity and college continuing education classes. He has a Bachelor ofScience degree in mathematics and computer science from BrandonUniversity in Brandon, Manitoba, Canada, and currently freelances in Javaand other software technologies.

xThis book was purchased by harshamv@variable3.com ■ CONTENTS

About the TechnicalReviewerPaul Connolly is the Director of Engineering for Atypon Systems'RightSuite product line. RightSuite is an enterprise access-control andcommerce solution used by many of the world's largest publishing andmedia companies. Paul enjoys designing and implementing high-performance, enterprise-class software systems. He is also an activecontributor in the open-source community.Prior to joining Atypon Systems, Paul worked as a senior softwareengineer at Standard & Poor's where he architected and developed keycommunications systems. Paul is a Sun Certified Java Programmer, SunCertified Business Component Developer, and a Sun Certified WebComponent Developer. Paul lives in New York City with his wife, Marina.

xi ■ CONTENTS

AcknowledgmentsI thank Steve Anglin for contacting me to write this book, Debra Kelly for guiding me through thevarious aspects of this project, Tom Welsh for helping me with the development of my chapters,Paul Connolly for his diligence in catching various flaws that would otherwise have made it intothis book, and Bill McManus and the production team for making the book’s content look good.It has been many years since I started writing about Java, and I also thank the followingeditors who have helped me share my knowledge with others: Chris Adamson, Bridget Collins,Richard Dal Porto, Sean Dixon, Victoria Elzey, Kevin Farnham, Todd Green, Jennifer Orr, AthenO’Shea, Esther Schindler, Daniel Steinberg, Jill Steinberg, Dustin Sullivan, and Atlanta Wilson.xii

IntroductionSmartphones and other touch-based mobile devices are all the rage these days. Their popularityis largely due to their ability to run apps. Although the iPhone and iPad with their growingcollection of Objective-C-based apps are the leaders of the pack, Android-based smartphoneswith their growing collection of Java-based apps are proving to be a strong competitor.Not only are many iPhone/iPad developers making money by selling their apps, manyAndroid developers are also making money by selling similar apps. According to tech websitessuch as The Register (www.theregister.co.uk/), some Android developers are making lots ofmoney (www.theregister.co.uk/2010/03/02/android_app_profit/).In today’s tough economic climate, perhaps you would like to try your hand at becoming anAndroid developer and make some money. If you have good ideas, perseverance, and someartistic talent (or perhaps know some talented individuals), you are already part of the waytoward achieving this goal.Tip: A good reason to consider Android app development over iPhone/iPad app development is the lowerstartup costs that you will incur with Android. For example, you do not need to purchase a Mac on which todevelop Android apps (a Mac is required for developing iPhone/iPad apps); your existing Windows, Linux,or Unix machine will do nicely.Most importantly, you will need to possess a solid understanding of the Java language andfoundational application programming interfaces (APIs) before jumping into Android. After all,Android apps are written in Java and interact with many of the standard Java APIs (such asthreading and input/output APIs).I wrote Learn Java for Android Development to give you a solid Java foundation that you canlater extend with knowledge of Android architecture, API, and tool specifics. This book will giveyou a strong grasp of the Java language and many important APIs that are fundamental toAndroid apps and other Java applications. It will also introduce you to key development tools.Learn Java for Android Development is organized into ten chapters and one appendix. Eachchapter focuses on a collection of related topics and presents a set of exercises that you shouldcomplete to get the most benefit from the chapter’s content. The appendix provides the solutionsto each chapter’s exercises.xiii ■ INTRODUCTIONNote: You can download this book’s source code by pointing your web browser towww.apress.com/book/view/1430231564 and clicking the Source Code link under Book Resources.Although most of this code is compilable with Java version 6, you will need Java version 7 to compile oneof the applications.Chapter 1 introduces you to Java by first focusing on Java’s dual nature (language andplatform). It then briefly introduces you to Sun’s/Oracle’s Java SE, Java EE, and Java ME editionsof the Java development software, as well as Google’s Android edition. You next learn how todownload and install the Java SE Development Kit (JDK), and learn some Java basics bydeveloping and playing with a pair of simple Java applications. After receiving a briefintroduction to the NetBeans and Eclipse IDEs, you learn about application development in thecontext of Four of a Kind, a console-based card game.Chapter 2 starts you on an in-depth journey of the Java language by focusing on languagefundamentals (such as types, expressions, variables, and statements) in the contexts of classesand objects. Because applications are largely based on classes, it is important to learn how toarchitect classes correctly, and this chapter shows you how to do so.Chapter 3 adds to Chapter 2’s pool of object-based knowledge by introducing you to thoselanguage features that take you from object-based applications to object-oriented applications.Specifically, you learn about features related to inheritance, polymorphism, and interfaces. Whileexploring inheritance, you learn about Java’s ultimate superclass. Also, while exploring interfaces,you discover the real reason for their inclusion in the Java language; interfaces are not merely aworkaround for Java’s lack of support for multiple implementation inheritance, but serve ahigher purpose.Chapter 4 introduces you to four categories of advanced language features: nested types,packages, static imports, and exceptions. While discussing nested types, I briefly introduce theconcept of a closure and state that closures will appear in Java version 7 (which many expect toarrive later this year).Note: I wrote this book several months before Java version 7’s expected arrival in the fall of 2010.Although I have tried to present an accurate portrayal of version 7–specific language features, it is possiblethat feature syntax may differ somewhat from what is presented in this book. Also, I only discuss closuresbriefly because this feature was still in a state of flux while writing this book. For more information aboutclosures and other functional programming concepts (such as lambdas) being considered for Java version 7, Irecommend that you check out articles such as “Functional Programming Concepts in JDK 7” by Alex Collinshttp://java.dzone.com/articles/lambdas-closures-jdk-7).(Chapter 5 continues to explore advanced language features by focusing on assertions,annotations, generics, and enums. Although the topic of generics has brought confusion to manydevelopers, I believe that my discussion of this topic will clear up much of the murkiness. Amongother items, you learn how to interpret type declarations such as Enum<E extends Enum<E>>.Chapter 6 begins a trend that focuses more on APIs than language features. This chapter firstintroduces you to many of Java’s math-oriented types (such as Math, StrictMath, BigDecimal, andBigInteger), and also introduces you to Java’s strictfp reserved word. It then looks at thePackage class, primitive wrapper classes, and the References API.xiv ■ INTRODUCTIONChapter 7 continues to explore Java’s basic APIs by focusing on reflection, stringmanagement, the System class, and threading.Chapter 8 focuses exclusively on Java’s collections framework, which provides you with asolution for organizing objects in lists, sets, queues, and maps.Chapter 9 continues to explore Java’s utility APIs by introducing you to the concurrencyutilities, internationalization, preferences, random number generation, and regular expressions.Chapter 10 is all about input/output (I/O). In this chapter, you explore Java’s classic I/Osupport in terms of its File class, RandomAccessFile class, various stream classes, and variouswriter/reader classes. My discussion of stream I/O includes coverage of Java’s object serializationand deserialization mechanisms.Note: This book largely discusses APIs that are common to Java SE and Android. However, it diverges fromthis practice in Chapter 9, where I use the Swing toolkit to provide a graphical user interface for one of thischapter’s internationalization examples. (Android does not support Swing.)After you complete this book, I recommend that you obtain a copy of Beginning Android 2 byMark L Murphy (Apress, 2010; ISBN: 1430226293) and start learning how to develop Androidapps. In that book, “you’ll learn how to develop applications for Android 2.x mobile devices,using simple examples that are ready to run with your copy of the JDK.”Note: Over the next few months, I will make available at my javajeff.mb.ca website six additional PDF-based chapters. These chapters will introduce you to more Java APIs (such as networking and databaseAPIs) that I could not discuss in this book because the book has greatly exceeded its initial 400-pageestimate (and the good folks at Apress have been gracious enough to let me do so, but there are limits). Ipresent more information about these PDF files at the end of Chapter 10’s “Summary” section.Thanks for purchasing my book. I hope you find it a helpful preparation for, and I wish youlots of success in achieving, a satisfying and lucrative career as an Android app developer.

Jeff “JavaJeff” Friesen, August 2010xv ■ INTRODUCTION

xvi1Chapter1Getting Started with JavaAndroid is Google’s software stack for mobile devices that includes an operating systemand middleware. With help from Java, the OS runs specially designed Java applicationsknown as Android apps. Because these apps are based on Java, it makes sense for youto learn about Java before you dive into the world of Android development.NOTE: This book illustrates Java concepts via non-Android Java applications.This chapter sets the stage for teaching you the essential Java concepts that you needto understand before you embark on your Android career. I first answer the “What isJava?” question. I next show you how to install the Java SE Development Kit, andintroduce you to JDK tools for compiling and running Java applications.After showing you how to install and use the open source NetBeans and Eclipse IDEs sothat you can develop these applications faster, I present an application for playing acard game that I call Four of a Kind. This application gives you a significant taste of theJava language, and is the centerpiece of my discussion on developing applications.What Is Java?Java is a language and a platform originated by Sun Microsystems. This section brieflydescribes this language and reveals what it means for Java to be a platform. To meetvarious needs, Sun organized Java into three main editions: Java SE, Java EE, and JavaME. This section also briefly explores each of these editions, along with Android.

1 CHAPTER 1: Getting Started with Java2NOTE: Java has an interesting history that dates back to December 1990. At that time, JamesGosling, Patrick Naughton, and Mike Sheridan (all employees of Sun Microsystems) were giventhe task of figuring out the next major trend in computing. They concluded that one trend wouldinvolve the convergence of computing devices and intelligent consumer appliances. Thus wasborn the Green project.The fruits of Green were Star7, a handheld wireless device featuring a five-inch color LCDscreen, a SPARC processor, a sophisticated graphics capability, and a version of Unix; and Oak, alanguage developed by James Gosling for writing applications to run on Star7, and which henamed after an oak tree growing outside of his office window at Sun. To avoid a conflict withanother language of the same name, Dr. Gosling changed this language’s name to Java.Sun Microsystems subsequently evolved the Java language and platform until Oracle acquiredSun in early 2010. Check out http://java.sun.com/ for the latest Java news from Oracle.Java Is a LanguageJava is a language in which developers express source code (program text). Java’ssyntax (rules for combining symbols into language features) is partly patterned after theC and C++ languages to shorten the learning curve for C/C++ developers.The following list identifies a few similarities between Java and C/C++:Java and C/C++ share the same single-line and multiline commentstyles. Comments let you document source code.Many of Java’s reserved words are identical to their C/C++counterparts (for, if, switch, and while are examples) and C++counterparts (catch, class, public, and try are examples).Java also supports character, double precision floating-point, floating-point, integer, long integer, and short integer primitive types, and viathe same char, double, float, int, long, and short reserved words.Java also supports many of the same operators, including arithmetic(+, -, *, /, and %) and conditional (?:) operators.Java also uses brace characters ({ and }) to delimit blocks ofstatements.The following list identifies a few differences between Java and C/C++:Java supports an additional comment style known as Javadoc. (I willbriefly introduce Javadoc later in this chapter.)Java provides reserved words not found in C/C++ (extends, strictfp,synchronized, and transient are examples). CHAPTER 1: Getting Started with Java3Java supports the byte integer type, does not provided a signedversion of the character type, and does not provide unsigned versionsof integer, long integer, and short integer. Furthermore, all of Java’sprimitive types have guaranteed implementation sizes, which is animportant part of achieving portability (discussed later). The samecannot be said of equivalent primitive types in C and C++.Java provides operators not found in C/C++. These operators includeinstanceof and >>> (unsigned right shift).Java provides labeled break and continue statements that you will notfind in C/C++.You will learn about single-line and multiline comments in Chapter 2. Also, you will learnabout reserved words, primitive types, operators, blocks, and statements (includinglabeled break and continue) in that chapter.Java was designed to be a safer language than C/C++. It achieves safety in part byomitting certain C/C++ features. For example, Java does not support pointers (variablescontaining addresses) and does not let you overload operators.Java also achieves safety by modifying certain C/C++ features. For example, loops mustbe controlled by Boolean expressions instead of integer expressions where 0 is falseand a nonzero value is true. (Chapter 2 discusses loops and expressions.)Suppose you must code a C/C++ while loop that repeats no more than ten times. Beingtired, you specify while (x) x++; (assume that x is an integer-based variable initializedto 0—I discuss variables in Chapter 2) where x++ adds 1 to x’s value. This loop does notstop when x reaches 10; you have introduced a bug (a defect).This problem is less likely to occur in Java because it complains when it sees while (x).This complaint requires you to recheck your expression, and you will then most likelyspecify while (x != 10). Not only is safety improved (you cannot specify just x),meaning is also clarified: while (x != 10) is more meaningful than while (x).The aforementioned and other fundamental language features support classes, objects,inheritance, polymorphism, and interfaces. Java also provides advanced features relatedto nested types, packages, static imports, exceptions, assertions, annotations, generics,enums, and more. Subsequent chapters explore all of these language features.Java Is a PlatformJava is a platform for executing programs. In contrast to platforms that consist ofphysical processors (such as an Intel processor) and operating systems (such as Linux),the Java platform consists of a virtual machine and associated execution environment.The virtual machine is a software-based processor that presents its own instruction set.The associated execution environment consists of libraries for running programs andinteracting with the underlying operating system. CHAPTER 1: Getting Started with Java4The execution environment includes a huge library of prebuilt classfiles that performcommon tasks, such as math operations (trigonometry, for example) and networkcommunications. This library is commonly referred to as the standard class library.A special Java program known as the Java compiler translates source code intoinstructions (and associated data) that are executed by the virtual machine. Theseinstructions are commonly referred to as bytecode.The compiler stores a program’s bytecode and data in files having the .class extension.These files are known as classfiles because they typically store the compiled equivalentof classes, a language feature discussed in Chapter 2.A Java program executes via a tool (such as java) that loads and starts the virtualmachine, and passes the program’s main classfile to the machine. The virtual machineuses a classloader (a virtual machine or execution environment component) to load theclassfile.After the classfile has been loaded, the virtual machine’s bytecode verifier componentmakes sure that the classfile’s bytecode is valid and does not compromise security. Theverifier terminates the virtual machine when it finds a problem with the bytecode.Assuming that all is well with the classfile’s bytecode, the virtual machine’s interpreterinterprets the bytecode one instruction at a time. Interpretation consists of identifyingbytecode instructions and executing equivalent native instructions.NOTE: Native instructions (also known as native code) are the instructions understood by theunderlying platform’s physical processor.When the interpreter learns that a sequence of bytecode instructions is executedrepeatedly, it informs the virtual machine’s Just In Time (JIT) compiler to compile theseinstructions into native code.JIT compilation is performed only once for a given sequence of bytecode instructions.Because the native instructions execute instead of the associated bytecode instructionsequence, the program executes much faster.During execution, the interpreter might encounter a request to execute anotherclassfile’s bytecode. When that happens, it asks the classloader to load the classfile andthe bytecode verifier to verify the bytecode prior to executing that bytecode.The platform side of Java promotes portability by providing an abstraction over theunderlying platform. As a result, the same bytecode runs unchanged on Windows-based, Linux-based, Mac OS X–based, and other platforms.This book was purchased by harshamv@variable3.comCHAPTER 1: Getting Started with Java5NOTE: Java was introduced with the “write once, run anywhere” slogan. Although Java goes togreat lengths to enforce portability, it does not always succeed. Despite being mostly platformindependent, certain parts of Java (such as the scheduling of threads, discussed in Chapter 7)vary from underlying platform to underlying platform.The platform side of Java also promotes security by providing a secure environment inwhich code executes. The goal is to prevent malicious code from corrupting theunderlying platform (and possibly stealing sensitive information).NOTE: Because many developers are not satisfied with the Java language, but believe that theJava platform is important, they have devised additional languages (such as Groovy) that run onthe Java platform. Furthermore, Java version 7 includes an enhanced virtual machine thatsimplifies adapting even more dynamic programming languages (languages that require less-rigid coding; you do not have to define a variable’s type before using the variable, for example) tothis platform.Java SE, Java EE, Java ME, and AndroidDevelopers use different editions of the Java platform to create Java programs that runon desktop computers, web browsers, web servers, mobile information devices (such ascell phones), and embedded devices (such as television set-top boxes):Java Platform, Standard Edition (Java SE): The Java platform fordeveloping applications, which are stand-alone programs that run ondesktops. Java SE is also used to develop applets, which areprograms that run in the context of a web browser.Java Platform, Enterprise Edition (Java EE): The Java platform fordeveloping enterprise-oriented applications and servlets, which areserver programs that conform to Java EE’s Servlet API. Java EE is builton top of Java SE.Java Platform, Micro Edition (Java ME): The Java platform fordeveloping MIDlets, which are programs that run on mobileinformation devices, and Xlets, which are programs that run onembedded devices.Developers also use a special Google-created edition of the Java platform (seehttp://developer.android.com/index.html) to create Android apps that run onAndroid-enabled devices. This edition is known as the Android platform.Google’s Android platform largely consists of Java core libraries (partly based on JavaSE) and a virtual machine known as Dalvik. This collective software runs on top of aspecially modified Linux kernel. CHAPTER 1: Getting Started with Java6NOTE: Check out Wikipedia’s “Android (operating system)” entry(http://en.wikipedia.org/wiki/Android_%28operating_system%29) to learn moreabout the Android OS, and Wikipedia’s “Dalvik (software)” entry(http://en.wikipedia.org/wiki/Dalvik_%28software%29) to learn more about theDalvik virtual machine.In this book, I cover the Java language (supported by Java SE and Android) and Java SEAPIs (also supported by Android). Furthermore, I present the source code (typically ascode fragments) to Java SE–based applications.Installing and Exploring the JDKThe Java Runtime Environment (JRE) implements the Java SE platform and makes itpossible to run Java programs. The public JRE can be downloaded from the Java SEDownloads page (http://java.sun.com/javase/downloads/index.jsp).However, the public JRE does not make it possible to develop Java programs. For thattask, you need to download and install the Java SE Development Kit (JDK), whichcontains development tools (including the Java compiler) and a private JRE.NOTE: JDK 1.0 was the first JDK to be released (in May 1995). Until JDK 6 arrived, JDK stood forJava Development Kit (SE was not part of the title). Over the years, numerous JDKs have beenreleased, with JDK 7 set for release in fall or winter 2010.Each JDK’s version number identifies a version of Java. For example, JDK 1.0 identifies Javaversion 1.0, and JDK 5 identifies Java version 5.0. JDK 5 was the first JDK to also provide aninternal version number: 1.5.0.The Java SE Downloads page also provides access to the current JDK, which is JDK 6Update 20 at time of writing. Click the Download JDK link to download the current JDK’sinstaller program for your platform.NOTE: Some of this book’s code requires JDK 7, which is only available as a preview release(http://java.sun.com/javase/downloads/ea.jsp) at time of writing.The JDK installer installs the JDK in a home directory. (It can also install the public JREin another directory.) On my Windows XP platform, the home directory is C:\ProgramFiles\Java\jdk1.6.0_16—JDK 6 Update 16 was current when I began this book. CHAPTER 1: Getting Started with Java7TIP: After installing the JDK, you should add the bin subdirectory to your platform’s PATHenvironment variable. That way, you will be able to execute JDK tools from any directory in yourfilesystem.Finally, you might want to create a projects subdirectory of the JDK’s home directory toorganize your Java projects, and create a separate subdirectory within projects for each ofthese projects.The home directory contains various files (such as README.html, which providesinformation about the JDK, and src.zip, which provides the standard class librarysource code) and subdirectories, including the following three important subdirectories:bin: This subdirectory contains assorted JDK tools, including the Javacompiler tool. You will discover some of these tools shortly.jre: This subdirectory contains the JDK’s private copy of the JRE,which lets you run Java programs without having to download andinstall the public JRE.lib: This subdirectory contains library files that are used by JDK tools.For example, tools.jar contains the Java compiler’s classfiles—thecompiler was written in Java.You will use only a few of the bin subdirectory’s tools in this book, specifically javac(Java compiler), java (Java application launcher), javadoc (Java documentationgenerator), and jar (Java archive creator, updater, and extractor).NOTE: javac is not the Java compiler. It is a tool that loads and starts the virtual machine,identifies the compiler’s main classfile (located in tools.jar) to the virtual machine, andpasses the name of the source file being compiled to the compiler’s main classfile.You execute JDK tools at the command line, passing command-line arguments to a tool.Learn about the command line and arguments via Wikipedia’s “Command-line interface”entry (http://en.wikipedia.org/wiki/Command-line_interface).Now that you have installed the JDK and know something about its tools, you are readyto explore a small DumpArgs application that outputs its command-line arguments to thestandard output device. CHAPTER 1: Getting Started with Java8NOTE: The standard output device is part of a mechanism known as Standard I/O. Thismechanism, which consists of Standard Input, Standard Output, and Standard Error, and whichoriginated with the Unix operating system, makes it possible to read text from different sources(keyboard or file) and write text to different destinations (screen or file).Text is read from the standard input device, which defaults to the keyboard but can be redirectedto a file. Text is output to the standard output device, which defaults to the screen but can beredirected to a file. Error message text is output to the standard error device, which defaults tothe screen but can be redirected to a file that differs from the standard output file.Listing 1–1 presents the DumpArgs application source code.Listing 1–1. Dumping command-line arguments via main()’s args array to the standard output devicepublic class DumpArgs{public static void main(String[] args){System.out.println("Passed arguments:");for (int i = 0; i < args.length; i++)System.out.println(args[i]);}}Listing 1–1’s DumpArgs application consists of a class named DumpArgs and a methodwithin this class named main(), which is the application’s entry point and provides thecode to execute. (You will learn about classes and methods in Chapter 2.)main() is called with an array of strings (character sequences) that identify theapplication’s command-line arguments. These strings are stored in String-based arrayvariable args. (I discuss method calling, arrays, and variables in Chapter 2.)NOTE: Although the array variable is named args, there is nothing special about this name. Youcould name this variable anything you want.main() first executes System.out.println("Passed arguments:");, which callsSystem.out’s println() method with the "Passed arguments:" string. This method calloutputs Passed arguments: to the standard output device and then terminates thecurrent line so that subsequent output is sent to a new line immediately below thecurrent line. (I discuss System.out in Chapter 7.) CHAPTER 1: Getting Started with Java9NOTE: System.out provides access to a family of println() methods and a family ofprint() methods for outputting different kinds of data (such as sequences of characters andintegers). Unlike the println() methods, the print() methods do not terminate the currentline; subsequent output continues on the current line.Each println() method terminates a line by outputting a line separator string, which is definedby system property line.separator, and which is not necessarily a single newline character(identified in source code via character literal '\n'). (I discuss system properties in Chapter 7,line.separator in Chapter 10, and character literals in Chapter 2.) For example, on Windowsplatforms, the line separator string is a carriage return character (whose integer code is 13)followed by a line feed character (whose integer code is 10).main() uses a for loop to repeatedly execute System.out.println(args[i]);. The loopexecutes args.length times, which happens to identify the number of strings that arestored in args. (I discuss for loops in Chapter 2.)The System.out.println(args[i]); method call reads the string stored in the ith entryof the args array—the first entry is located at index (location) 0; the last entry is stored atindex args.length - 1. This method call then outputs this string to standard output.Assuming that you are familiar with your platform’s command-line interface and are atthe command line, make DumpArgs your current directory and copy Listing 1–1 to a filenamed DumpArgs.java. Then compile this source file via the following command line:javac DumpArgs.javaAssuming that that you have included the .java extension, which is required by javac,and that DumpArgs.java compiles, you should discover a file named DumpArgs.class inthe current directory. Run this application via the following command line:java DumpArgsIf all goes well, you should see the following line of output on the screen:Passed arguments:For more interesting output, you will need to pass command-line arguments toDumpArgs. For example, execute the following command line, which specifies Curly, Moe,and Larry as three arguments to pass to DumpArgs:java DumpArgs Curly Moe LarryThis time, you should see the following expanded output on the screen:Passed arguments:CurlyMoeLarry CHAPTER 1: Getting Started with Java10You can redirect the output destination to a file by specifying the greater than anglebracket (>) followed by a filename. For example, java DumpArgs Curly Moe Larry>out.txt stores the DumpArgs application’s output in a file named out.txt.NOTE: Instead of specifying System.out.println(), you could specifySystem.err.println() to output characters to the standard error device. (System.errprovides the same families of println() and print() methods as System.out.) However,you should only switch from System.out to System.err when you need to output an errormessage so that the error messages are displayed on the screen, even when standard output isredirected to a file.Congratulations on successfully compiling your first application source file and runningthe application! Listing 1–2 presents the source code to a second application, whichechoes text obtained from the standard input device to the standard output device.Listing 1–2. Echoing text read from standard input to standard outputpublic class EchoText{public static void main(String[] args) throws java.io.IOException{System.out.println("Please enter some text and press Enter!");int ch;while ((ch = System.in.read()) != 13)System.out.print((char) ch);System.out.println();}}After outputting a message that prompts the user to enter some text, main() introducesint variable ch to store each character’s integer representation. (You will learn about intand integer in Chapter 2.)main() now enters a while loop (discussed in Chapter 2) to read and echo characters.The loop first calls System.in.read() to read a character and assign its integer value toch. The loop ends when this value equals 13 (the integer value of the Enter key).NOTE: When standard input is not redirected to a file, System.in.read() returns 13 toindicate that the Enter key has been pressed. On platforms such as Windows, a subsequent callto System.in.read() returns integer 10, indicating a line feed character. Whether or notstandard input has been redirected, System.in.read() returns -1 when there are no morecharacters to read.For any other value in ch, this value is converted to a character via (char), which is anexample of Java’s cast operator (discussed in Chapter 2). The character is then outputvia System.out.println(). The final System.out.println(); call terminates the currentline without outputting any content. CHAPTER 1: Getting Started with Java11NOTE: When standard input is redirected to a file and System.in.read() is unable to read textfrom the file (perhaps the file is stored on a removable storage device that has been removed prior tothe read operation), System.in.read() fails by throwing an object that describes this problem. Iacknowledge this possibility by appending throws java.io.IOException to the end of themain() method header. I discuss throws in Chapter 4 and java.io.IOException in Chapter 10.Compile Listing 1–2 via javac EchoText.java, and run the application via java EchoText.You will be prompted to enter some text. After you input this text and press Enter, thetext will be sent to standard output. For example, consider the following output:Please enter some text and press Enter!Hello JavaHello JavaYou can redirect the input source to a file by specifying the less than angle bracket (<)followed by a filename. For example, java EchoText <EchoText.java reads its text fromEchoText.java and outputs this text to the screen.Run this application and you will only see EchoText.java’s first line of text. Each one ofthis file’s lines ends in a carriage return character (13) (followed by a line feed character,10, on Windows platforms), and EchoText terminates after reading a carriage return.In addition to downloading and installing the JDK, you might want to download theJDK’s companion documentation archive file (jdk-6u18-docs.zip is the most recent fileat time of writing).After downloading the documentation archive file from the same Java SE Downloadspage (http://java.sun.com/javase/downloads/index.jsp), unzip this file and move itsdocs directory to the JDK’s home directory.To access the documentation, point your web browser to the documentation’s startpage. For example, after moving docs to my JDK’s home directory, I point my browser toC:\Program Files\Java\jdk1.6.0_16\docs\index.html. See Figure 1–1.Scroll a bit down the start page and you discover the “API, Language, and VirtualMachine Documentation” section, which presents a Java 2 Platform API Specificationlink. Click this link and you can access the standard class library’s documentation.TIP: You can read the online documentation by pointing your web browser to a link such ashttp://download.java.net/jdk6/archive/b104/docs/, which provides the onlinedocumentation for JDK 6. CHAPTER 1: Getting Started with Java12

Figure 1–1. The first part of the Java documentation’s start pageInstalling and Exploring Two Popular IDEsWorking with the JDK’s tools at the command line is probably okay for small projects.However, this practice is not recommended for large projects, which are hard to managewithout the help of an integrated development environment (IDE).An IDE consists of a project manager for managing a project’s files, a text editor forentering and editing source code, a debugger for locating bugs, and other features. Twopopular IDEs are NetBeans and Eclipse.NOTE: For convenience, I use JDK tools throughout this book, except for this section where I useNetBeans IDE and Eclipse IDE. CHAPTER 1: Getting Started with Java13NetBeans IDENetBeans IDE is an open source, Java-based IDE for developing programs in Java andother languages (such as PHP, Ruby, C++, Groovy, and Scala). Version 6.8 is the currentversion of this IDE at time of writing.You should download and install NetBeans IDE 6.8 (or a more recent version) to followalong with this section’s NetBeans-oriented example. Begin by pointing your browser tohttp://netbeans.org/downloads/ and accomplishing the following tasks:1. Select an appropriate IDE language (such as English).2. Select an appropriate platform (such as Linux).3. Click the Download button underneath the leftmost (Java SE) column.After a few moments, the current page is replaced by another page that gives you theopportunity to download an installer file. I downloaded the approximately 47MBnetbeans-6.8-ml-javase-windows.exe installer file for my Windows XP platform.NOTE: According to the “NetBeans IDE 6.8 Installation Instructions”(http://netbeans.org/community/releases/68/install.html), you must install JDK5.0 Update 19 or JDK 6 Update 14 or newer on your platform before installing NetBeans IDE 6.8.If you do not have a JDK installed, you cannot install the NetBeans IDE.Start the installer file and follow the instructions. You will need to agree to the NetBeanslicense, and are given the options of providing anonymous usage data and registeringyour copy of NetBeans when installation finishes.Assuming that you have installed the NetBeans IDE, start this Java application. Youshould discover a splash screen identifying this IDE, followed by a main window similarto that shown in Figure 1–2.The NetBeans user interface is based on a main window that consists of a menu bar, atoolbar, a workspace area, and a status bar. The workspace area initially presents aStart Page tab, which provides NetBeans tutorials as well as news and blogs.To help you get comfortable with the NetBeans user interface, I will show you how tocreate a DumpArgs project containing a single DumpArgs.java source file with Listing 1–1’ssource code. You will also learn how to compile and run this application. CHAPTER 1: Getting Started with Java14

Figure 1–2. The NetBeans IDE 6.8 main windowComplete the following steps to create the DumpArgs project:1. Select New Project from the File menu.2. On the resulting New Project dialog box’s initial pane, make sure thatJava is the selected category in the Categories list, and Java Applicationis the selected project in the Projects list. Click the Next button.3. On the resulting pane, enter DumpArgs in the Project Name text field.You will notice that dumpargs.Main appears in the text field to the rightof the Create Main Class check box. Replace dumpargs.Main withDumpArgs and click Finish. (dumpargs names a package, discussed inChapter 4, and Main names a class stored in this package.)After a few moments, you will see a workspace similar to that shown in Figure 1–3.This book was purchased by harshamv@variable3.comCHAPTER 1: Getting Started with Java15

Figure 1–3. The workspace is divided into multiple work areas.After creating the DumpArgs project, you will discover that NetBeans has organized theworkspace into four main areas: projects, editor, navigator, and tasks.The projects area helps you manage your projects. This window is divided into Projects,Files, and Services tabs:The Projects tab is the main entry point to your project’s source andresource files. It presents a logical view of important project contents.The Files tab presents a directory-based view of your projects,including any files and folders that are not displayed on the Projectstab.The Services tab is the main entry point to runtime resources. It showsa logical view of important runtime resources such as the servers,databases, and web services that are registered with the IDE.The editor area helps you edit a project’s source files. Each file has its own tab, labeledwith the file’s name.Figure 1–3 reveals a single DumpArgs.java tab, which provides access to skeletal sourcecode. You will shortly replace this source code with Listing 1–1. CHAPTER 1: Getting Started with Java16The skeletal source code reveals single-line and multiline comments (discussed inChapter 2) and Javadoc comments (discussed later in this chapter).The navigator area reveals the Navigator tab, which presents a compact view of thecurrently selected file and simplifies navigation between different parts of the file.The tasks area reveals the Tasks tab, which presents a to-do list of items for theproject’s various files that need to be resolved.Replace the skeletal DumpArgs.java source code with Listing 1–1, and select Run MainProject from the Run menu to compile and run this application. Figure 1–4 shows thisapplication’s results.

Figure 1–4. An Output tab appears to the left of the Tasks tab and shows the DumpArgs application’s output.Figure 1–4’s Output tab reveals only the result of the System.out.println("Passedarguments:") method call. To see more output, you must pass command-linearguments to DumpArgs. Accomplish this task from within NetBeans IDE 6.8 as follows:1. Select Project Properties (DumpArgs) from the File menu.2. In the resulting Project Properties dialog box, select Run in theCategories tree and enter Curly Moe Larry in the Arguments text fieldon the resulting pane. Click the OK button. CHAPTER 1: Getting Started with Java17Once again, select Run Main Project from the Run menu to run the DumpArgs application.This time, the Output tab should reveal Curly, Moe, and Larry on separate lines belowPassed arguments:.This is all I have to say about the NetBeans IDE. For more information, study the tutorialsvia the Start Page tab, access IDE help via the Help menu, and explore the NetBeansknowledge base at http://netbeans.org/kb/.Eclipse IDEEclipse IDE is an open source IDE for developing programs in Java and other languages(such as C, COBOL, PHP, Perl, and Python). Eclipse Classic is one distribution of thisIDE that is available for download; version 3.5.2 is the current version at time of writing.You should download and install Eclipse Classic to follow along with this section’sEclipse-oriented example. Begin by pointing your browser tohttp://www.eclipse.org/downloads/ and accomplishing the following tasks:1. Scroll down the page until you see an Eclipse Classic entry.2. Click one of the platform links (such as Linux 32 Bit) to the right of thisentry.3. Select a download mirror from the subsequently displayed page andproceed to download the distribution’s archive file.I downloaded the approximately 163MB eclipse-SDK-3.5.2-win32.zip archive file formy Windows XP platform, unarchived this file, moved the resulting eclipse homedirectory to another location, and created a shortcut to that directory’s eclipse.exe file.NOTE: Unlike NetBeans IDE 6.8, which requires that a suitable JDK be installed before you canrun the installer, a JDK does not have to be installed before running eclipse.exe because theEclipse IDE comes with its own Java compiler. However, you will need at least JDK 6 Update 16to run most of this book’s code (or JDK 7 to run all of the code).Assuming that you have installed Eclipse Classic, start this application. You shoulddiscover a splash screen identifying this IDE and a dialog box that lets you choose thelocation of a workspace for storing projects, followed by a main window like that shownin Figure 1–5.The Eclipse user interface is based on a main window that consists of a menu bar, atoolbar, a workbench area, and a status bar. The workbench area initially presents aWelcome tab with icon links for accessing tutorials and more.To help you get comfortable with the Eclipse user interface, I will show you how tocreate a DumpArgs project containing a single DumpArgs.java source file with Listing 1–1’ssource code. You will also learn how to compile and run this application. CHAPTER 1: Getting Started with Java18

Figure 1–5. The Eclipse IDE 3.5.2 main windowComplete the following steps to create the DumpArgs project:1. Select New from the File menu and Java Project from the resulting pop-up menu.2. In the resulting New Java Project dialog box, enter DumpArgs into theProject name text field. Keep all the other defaults and click the Finishbutton.3. Click the rightmost (Workbench) icon link to go to the workbench.Eclipse bypasses the Welcome tab and takes you to the workbench thenext time you start this IDE.TIP: To return to the Welcome tab, select Welcome from the Help menu.After the final step, you will see a workbench similar to that shown in Figure 1–6. CHAPTER 1: Getting Started with Java19

Figure 1–6. The workbench is divided into multiple work areas.On the left side of the workbench, you see a tab titled Package Explorer. This tabidentifies the workspace’s projects in terms of packages (discussed in Chapter 4). At themoment, only a single DumpArgs entry appears on this tab.Clicking the + icon to the left of DumpArgs expands this entry to reveal src and JRESystem Library items. The src item stores the DumpArgs project’s source files, and JRESystem Library identifies various JRE files that are used to run this application.We will now add a new file named DumpArgs.java to src, as follows:1. Highlight src and select New from the File menu, and File from theresulting pop-up menu.2. In the resulting New File dialog box, enter DumpArgs.java into the Filename text field, and click the Finish button.Eclipse responds by displaying an editor tab titled DumpArgs.java. Copy Listing 1–1 intothis tab, and then compile and run this application by selecting Run from the Run menu.Figure 1–7 shows the results. CHAPTER 1: Getting Started with Java20

Figure 1–7. The Console tab at the bottom of the workbench presents the DumpArgs application’s output.As with the NetBeans IDE, you must pass command-line arguments to DumpArgs to seeadditional output from this application. Accomplish this task from within Eclipse IDE3.5.2 as follows:1. Select Run Configurations from the Run menu.2. In the resulting Run Configurations dialog box, select the Argumentstab.3. Enter Curly Moe Larry into the Program arguments text area and clickthe Close button.Once again, select Run from the Run menu to run the DumpArgs application. This time,the Console tab reveals Curly, Moe, and Larry on separate lines below Passedarguments:.This is all I have to say about the Eclipse IDE. For more information, study the tutorialsvia the Welcome tab, access IDE help via the Help menu, and explore the Eclipsedocumentation at http://www.eclipse.org/documentation/.Four of a KindApplication development is not an easy task. If you do not plan carefully before youdevelop an application, you will probably waste your time and money as you endeavorto create it, and waste your users’ time and money if it does not meet their needs. CHAPTER 1: Getting Started with Java21CAUTION: It is extremely important to carefully test your software. You could face a lawsuit ifmalfunctioning software causes financial harm to its users.In this section, I present one technique for developing applications efficiently. I presentthis technique in the context of a Java application that lets you play a simple card gamecalled Four of a Kind against the computer.Understanding Four of a KindBefore sitting down at the computer and writing code, we need to fully understand theproblem domain that we are trying to model via that code. In this case, the problemdomain is Four of a Kind, and we want to understand how this card game works.Two to four players play Four of a Kind with a standard 52-card deck. The object of thegame is to be the first player to put down four cards that have the same rank (four aces,for example), which wins the game.The game begins by shuffling the deck and placing it face down. Each player takes acard from the top of the deck. The player with the highest ranked card (king is highest)deals four cards to each player, starting with the player to the dealer’s left. The dealerthen starts his/her turn.The player examines his/her cards to determine which cards are optimal for achievingfour of a kind. The player then throws away the least helpful card on a discard pile andpicks up another card from the top of the deck. (If each card has a different rank, theplayer randomly selects a card to throw away.) If the player has four of a kind, the playerputs down these cards (face up) and wins the game.Modeling Four of a Kind in PseudocodeNow that we understand how Four of a Kind works, we can begin to model this game.We will not model the game in Java source code because we would get bogged down intoo many details. Instead, we will use pseudocode for this task.Pseudocode is a compact and informal high-level description of the problem domain.Unlike the previous description of Four of a Kind, the pseudocode equivalent is a step-by-step recipe for solving the problem. Check out Listing 1–3.Listing 1–3. Four of a Kind pseudocode for two players (human and computer)1. Create a deck of cards and shuffle the deck.2. Create empty discard pile.3. Have each of the human and computer players take a card from the top of the deck.4. Designate the player with the highest ranked card as the current player.5. Return both cards to the bottom of the deck.6. The current player deals four cards to each of the two players in alternatingfashion, with the first card being dealt to the other player. CHAPTER 1: Getting Started with Java227. The current player examines its current cards to see which cards are optimal forachieving four of a kind. The current player throws the least helpful card onto the topof the discard pile.8. The current player picks up the deck's top card. If the current player has four of akind, it puts down its cards and wins the game.9. Designate the other player as the current player.10. If the deck has no more cards, empty the discard pile to the deck and shuffle thedeck.11. Repeat at step 7.Deriving Listing 1–3’s pseudocode from the previous description is the first step inachieving an application that implements Four of a Kind. This pseudocode performsvarious tasks, including decision making and repetition.Despite being a more useful guide to understanding how Four of a Kind works, Listing1–3 is too high level for translation to Java. Therefore, we must refine this pseudocodeto facilitate the translation process. Listing 1–4 presents this refinement.Listing 1–4. Refined Four of a Kind pseudocode for two players (human and computer)1. deck = new Deck()2. deck.shuffle()3. discardPile = new DiscardPile()4. hCard = deck.deal()5. cCard = deck.deal()6. if hCard.rank() == cCard.rank()6.1. deck.putBack(hCard)6.2. deck.putBack(cCard)6.3. deck.shuffle()6.4. Repeat at step 47. curPlayer = HUMAN7.1. if cCard.rank() > hCard.rank()7.1.1. curPlayer = COMPUTER8. deck.putBack(hCard)9. deck.putBack(cCard)10. if curPlayer == HUMAN10.1. for i = 0 to 310.1.1. cCards[i] = deck.deal()10.1.2. hCards[i] = deck.deal()else10.2. for i = 0 to 310.2.1. hCards[i] = deck.deal()10.2.2. cCards[i] = deck.deal()11. if curPlayer == HUMAN11.01. output(hCards)11.02. choice = prompt("Identify card to throw away")11.03. discardPile.setTopCard(hCards[choice])11.04. hCards[choice] = deck.deal()11.05. if isFourOfAKind(hCards)11.05.1. output("Human wins!")11.05.2. putDown(hCards)11.05.3. output("Computer's cards:")11.05.4. putDown(cCards)11.05.5. End game11.06. curPlayer = COMPUTER CHAPTER 1: Getting Started with Java23else11.07. choice = leastDesirableCard(cCards)11.08. discardPile.setTopCard(cCards[choice])11.09. cCards[choice] = deck.deal()11.10. if isFourOfAKind(cCards)11.10.1. output("Computer wins!")11.10.2. putDown(cCards)11.10.3. End game11.11. curPlayer = HUMAN12. if deck.isEmpty()12.1. if discardPile.topCard() != null12.1.1. deck.putBack(discardPile.getTopCard())12.1.2. Repeat at step 12.1.12.2. deck.shuffle()13. Repeat at step 11.In addition to being longer than Listing 1–3, Listing 1–4 shows the refined pseudocodebecoming more like Java. For example, Listing 1–4 reveals Java expressions (such asnew Deck(), to create a Deck object), operators (such as ==, to compare two values forequality), and method calls (such as deck.isEmpty(), to call deck’s isEmpty() method toreturn a Boolean value indicating whether [true] or not [false] the deck identified by deck