Learn the Java skills you will need to start developing Android apps

  Learn the Java skills you will need to start developing Android apps

  Learn

  • for

  Java Android Development

  THIRD EDITION Jeff Friesen

  

For your convenience Apress has placed some of the front

matter material after the index. Please use the Bookmarks

and Contents at a Glance links to access them.

  Contents at a Glance

About the Author ...............................................................................................................

Acknowledgments ............................................................................................................

Chapter 1: Getting Started with Java ................................................................................

   ■

Chapter 2: Learning Language Fundamentals .................................................................

   ■

Chapter 3: Discovering Classes and Objects ...................................................................

   ■

  

Chapter 4: Discovering Inheritance, Polymorphism, and Interfaces .............................

  

Chapter 5: Mastering Advanced Language Features, Part 1 .........................................

  

Chapter 6: Mastering Advanced Language Features, Part 2 .........................................

  

Chapter 7: Exploring the Basic APIs, Part 1 ..................................................................

  

Chapter 8: Exploring the Basic APIs, Part 2

  

Chapter 9: Exploring the Collections Framework

  

Chapter 10: Exploring the Concurrency Utilities ............................................................

  

Chapter 11: Performing Classic I/O ...............................................................................

  

Chapter 12: Accessing Networks ..................................................................................

v

  vi Contents at a Glance ■

  

Chapter 13: Migrating to New I/O ............................................................................

  

Chapter 14: Accessing Databases ...........................................................................

  

Chapter 15: Parsing, Creating, and Transforming XML Documents .........................

  

Chapter 16: Focusing on Odds and Ends .................................................................

■ Appendix A: Solutions to Exercises .......................................................................

Index .........................................................................................................................

  Introduction

  Smartphones and tablets are all the rage these days. Their popularity is largely due to their ability to run apps. Although the iPhone and iPad, with their growing collection of Objective-C based apps, had a head start, Android-based smartphones and tablets, with their growing collection of Java-based apps, have proven to be a strong competitor.

  Not only are many iPhone/iPad app developers making money by selling their apps, but many Android app developers are also making money by selling similar apps. According to tech web sites ), some Android app developers are making lots of

  

  money (

  

  In today’s challenging economic climate, you might like to try your hand at developing Android apps and make some money. If you have good ideas, perseverance, and some artistic talent (or perhaps know some talented individuals), you are already part of the way toward achieving this goal.

  Tip A good reason to consider Android app development over iPhone/iPad app development is the lower

  startup costs that you’ll incur with Android. For example, you don’t need to purchase a Mac on which to develop Android apps (a Mac is required for developing iPhone/iPad apps); your existing Windows, Linux, or Unix machine will do nicely.

  Most importantly, you’ll need to possess a solid understanding of the Java language and foundational 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 as threading and input/output APIs).

  I wrote Learn Java for Android Development to give you a solid Java foundation that you can later extend with knowledge of Android architecture, API, and tool specifics. This book will give you a strong grasp of the Java language and the many important APIs that are fundamental to Android apps and other Java applications. It will also introduce you to key development tools.

  xxvii xxviii Introduction Book Organization

  The first edition of this book was organized into 10 chapters and 1 appendix. The second edition was organized into 14 chapters and 3 appendixes. This third edition is organized into 16 chapters and 2 appendixes with a bonus appendix on Android app development. Each chapter in each edition offers a set of exercises that you should complete to get the most benefit from its content. Their solutions are presented in Appendix A.

  Chapter 1 introduces you to Java by first focusing on Java’s dual nature (language and platform). It then briefly introduces you to Oracle’s Java SE, Java EE, and Java ME editions of the Java platform. You next learn how to download and install the Java SE Development Kit (JDK), and you learn some Java basics by developing and playing with three simple Java applications. After receiving a brief introduction to the Eclipse IDE, you receive a brief introduction to Android. Chapter 2 starts you on an in-depth journey of the Java language by focusing on language fundamentals. You first learn about simple application structure and then learn about comments, identifiers (and reserved words), types, variables, expressions (and literals), and statements.

  Chapter 3 continues your journey by focusing on classes and objects. You learn how to declare a class and organize applications around multiple classes. You then learn how to construct objects from classes, declare fields in classes and access these fields, declare methods in classes and call them, initialize classes and objects, and remove objects when they’re no longer needed. You also learn more about arrays, which were first introduced in Chapter 2.

  Chapter 4 adds to Chapter 3’s pool of object-based knowledge by introducing you to the language features that take you from object-based applications to object-oriented applications. Specifically, you learn about features related to inheritance, polymorphism, and interfaces. While exploring inheritance, you learn about Java’s ultimate superclass. Also, while exploring interfaces, you discover why they were included in the Java language; interfaces are not merely a workaround for Java’s lack of support for multiple implementation inheritance, but serve a higher purpose.

  Chapter 5 introduces you to four categories of advanced language features: nested types, packages, static imports, and exceptions. Chapter 6 introduces you to four additional advanced language feature categories: assertions, annotations, generics, and enums. Chapter 7 begins a trend that focuses more on APIs than language features. This chapter first introduces you to Java’s Math and StrictMath math-oriented types. It then explores Number and its various subtypes (such as Integer, Double, and BigDecimal). Next you explore the string-oriented types (String, StringBuffer, and StringBuilder) followed by the System type. Finally, you explore the Thread class and related types for creating multithreaded applications.

  Chapter 8 continues to explore Java’s basic APIs by focusing on the Random class for generating random numbers; the References API, Reflection, the StringTokenizer class for breaking a string into smaller components; and the Timer and TimerTask classes for occasionally or repeatedly executing tasks.

  Chapter 9 focuses exclusively on Java’s Collections Framework, which provides you with a solution for organizing objects in lists, sets, queues, and maps. You also learn about collection-oriented utility classes and review Java’s legacy collection types.

  Introduction xxix

  Chapter 10 focuses exclusively on Java’s Concurrency Utilities. After receiving an introduction to this framework, you explore executors, synchronizers (such as countdown latches), concurrent collections, the Locking Framework, and atomic variables (where you discover compare-and-swap).

  Chapter 11 is all about classic input/output (I/O), largely from a file perspective. In this chapter, you explore classic I/O in terms of the File class, RandomAccessFile class, various stream classes, and various writer/reader classes. My discussion of stream I/O includes coverage of Java’s object serialization and deserialization mechanisms.

  Chapter 12 continues to explore classic I/O by focusing on networks. You learn about the Socket, ServerSocket, DatagramSocket, and MulticastSocket classes along with related types. You also learn about the URL class for achieving networked I/O at a higher level and learn about the related URI class. After learning about the low-level NetworkInterface and InterfaceAddress classes, you explore cookie management, in terms of the CookieHandler and CookieManager classes, and the CookiePolicy and CookieStore interfaces.

  Chapter 13 introduces you to New I/O. You learn about buffers, channels, selectors, regular expressions, charsets, and the Formatter and Scanner types in this chapter. Chapter 14 focuses on databases. You first learn about the Java DB and SQLite database products, and then explore JDBC for communicating with databases created via these products. Chapter 15 emphasizes Java’s support for XML. I first provide a tutorial on this topic where you learn about the XML declaration, elements and attributes, character references and CDATA sections, namespaces, comments and processing instructions, well-formed documents, and valid documents (in terms of Document Type Definition and XML Schema). I then show you how to parse

  XML documents via the SAX API, parse and create XML documents via the DOM API, parse XML documents via the XMLPULL V1 API (supported by Android as an alternative to Java’s StAX API), use the XPath API to concisely select nodes via location path expressions, and transform XML documents via XSLT.

  Chapter 16 completes the chapter portion of this book by covering odds and ends. You first learn about useful Java 7 language features that I’ve successfully used in Android apps. Next, you explore classloaders, the Console class, design patterns (with emphasis on the Strategy pattern), double brace initialization, fluent interfaces, immutability, internationalization (in terms of locales; resource bundles; break iterators; collators; dates, time zones, and calendars; and formatters), the Logging API, the Preferences API, the Runtime and Process classes, the Java Native Interface, and the ZIP and JAR APIs.

  Appendix A presents solutions to all of the exercises in Chapters 1 through 16. Appendix B introduces you to application development in the context of Four of a Kind, a console-based card game.

  Appendix C provides an introduction to Android app development. It gives you a chance to see how various Java language features and APIs are used in an Android context. Unlike the other elements, Appendix C is not included in this book—it’s included with the book’s source code. Appendix C doesn’t officially belong in Learn Java for Android Development because this book’s focus is to prepare you for getting into Android app development by teaching you the fundamentals of the Java language, and Appendix C goes beyond that focus by giving you a tutorial on Android app development. Besides, the presence of this appendix would cause the book to exceed the 1,200-page print-on-demand limit. xxx Introduction Note You can download this book’s source code by pointing your web browser to

licking the Source Code tab followed by the Download Now link.

  What Comes Next?

  After you complete this book, I recommend that you check out Apress’s other Android-oriented books, such as Beginning Android 4 by Grant Allen (Apress, 2012), and learn more about developing Android apps. In that book, you learn Android basics and how to create “innovative and salable applications for Android 4 mobile devices.” Thanks for purchasing this third (and my final) edition of Learn Java for Android Development. I hope you find it a helpful preparation for, and I wish you lots of success in achieving, a satisfying and lucrative career as an Android app developer.

  —Jeff Friesen, January 2014

  Chapter

  1 Getting Started with Java Android apps are written in Java and use various Java application program interfaces (APIs).

  Because you’ll want to write your own apps, but may be unfamiliar with the Java language and these APIs, this book teaches you about Java as a first step into Android app development. It provides you with Java language fundamentals and Java APIs that are useful when developing apps.

  Note This book illustrates Java concepts via non-Android Java applications. It’s easier for beginners to

  grasp these applications than corresponding Android apps. However, I also reveal a trivial Android app toward the end of this chapter for comparison purposes. An API is an interface that application code uses to communicate with other code, which is typically stored in a software library. For more information on this term, check out Wikipedia’s “Application programming

  

  interface” topic at This chapter sets the stage for teaching you the essential Java concepts that you need to understand before embarking on an Android app development career. I first answer the question: “What is Java?” Next, I show you how to install the Java SE Development Kit (JDK) and introduce you to JDK tools for compiling and running Java applications. After presenting a few simple example applications, I show you how to install and use the open source Eclipse IDE (integrated development environment) so that you can more easily (and more quickly) develop Java applications and (eventually) Android apps. I then provide you with a brief introduction to Android and show you how Java fits into the Android development paradigm.

  1

  2

CHAPTER 1: Getting Started with Java

  What Is Java?

Java is a language and a platform originated by Sun Microsystems. In this section, I briefly describe

  this language and reveal what it means for Java to be a platform. To meet various needs, Sun organized Java into three main editions: Java SE, Java EE, and Java ME. This section briefly explores each of these editions.

  Note Java has an interesting history that dates back to December 1990. At that time, James Gosling,

  Patrick Naughton, and Mike Sheridan (all employees of Sun Microsystems) were given the task of figuring out the next major trend in computing. They concluded that one trend would involve the convergence of computing devices and intelligent consumer appliances. Thus was born the Green Project. The fruits of Green were Star7, a handheld wireless device featuring a five-inch color LCD screen, a SPARC processor, a sophisticated graphics capability, a version of Unix, and Oak, a language developed by James Gosling for writing applications to run on Star7 that he named after an oak tree growing outside of his office window at Sun. To avoid a conflict with another 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 acquired Sun in early 2010. for the latest Java news from Oracle.

  Java Is a Language

  Java is a language in which developers express source code (program text). Java’s syntax (rules for combining symbols into language features) is partly patterned after the C and C++ languages in order 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 multi-line comment styles.  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 supports character, double precision floating-point, floating-point, integer,  long integer, and short integer primitive types via the same char, double, float, int, long, and short reserved words. Java supports many of the same operators, including arithmetic ( 

  • , -, *, /, and %) and conditional (?:) operators. Java uses brace characters (  { and }) to delimit blocks of statements.

CHAPTER 1: Getting Started with Java

  3

  The following list identifies a few of the differences between Java and C/C++:  Java supports an additional comment style known as Javadoc.

   Java provides reserved words not found in C/C++ (

  extends, strictfp, synchronized, and transient are examples).

   Java doesn’t require machine-specific knowledge. It supports the byte integer

   ), doesn’t

  

  provide a signed version of the character type, and doesn’t provide unsigned versions of integer, long integer, and short integer. Furthermore, all of Java’s primitive types have guaranteed implementation sizes, which is an important part of achieving portability (discussed later). The same cannot be said of equivalent primitive types in C and C++.

   Java provides operators not found in C/C++. These operators include instanceof and >>> (unsigned right shift).  Java provides labeled break and continue statements that you’ll not find in C/C++.

  You’ll learn about single-line, multi-line, and Javadoc comments in Chapter 2. Also, you’ll learn about reserved words, primitive types, operators, blocks, and statements (including labeled break and labeled continue) in that chapter. Java was designed to be a safer language than C/C++. It achieves safety in part by not letting you overload operators and by omitting C/C++ features such as pointers (storage locations containing addr ).

  

  Java also achieves safety by modifying certain C/C++ features. For example, loops must be controlled by Boolean expressions instead of integer expressions where 0 is false and a nonzero value is true. (There is a discussion of loops and expressions in Chapter 2.) Suppose you must code a C/C++ while loop that repeats no more than 10 times. Being tired, you specify the following: while (x) x++; Assume that x is an integer-based variable initialized to 0 (I discuss variables in Chapter 2). This loop repeatedly executes x++ to add 1 to x’s value. This loop doesn’t stop when x reaches 10; you have introduced a bug. 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 likely specify while (x != 10). Not only is safety improved (you cannot specify just x), but meaning is also clarified: while (x != 10) is more meaningful than while (x).

  These and other fundamental language features support classes, objects, inheritance, polymorphism, and interfaces. Java also provides advanced features related to nested types, packages, static imports, exceptions, assertions, annotations, generics, enums, and more. Subsequent chapters explore most of these language features.

  4

CHAPTER 1: Getting Started with Java

  Java Is a Platform

  Java is a platform consisting of a virtual machine and an execution environment. The virtual machine is a software-based processor that presents an instruction set, and it is commonly referred to as the

  Java Virtual Machine (JVM). The execution environment consists of libraries for running programs and interacting with the underlying operating system (also known as the native platform).

  The execution environment includes a huge library of prebuilt classfiles that perform common tasks, such as math operations (trigonometry, for example) and network communications. This library is commonly referred to as the standard class library. A special Java program known as the Java compiler translates source code into object code consisting of instructions that are executed by the JVM and associated data. These instructions are known as bytecode. Figur shows this translation process.

  

Java Java

Java

Source Object

Compiler

  Code Code Figure 1-1. The Java compiler translates Java source code into Java object code consisting of bytecode and associated data

  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 equivalent of classes, a language feature discussed in Chapter 3. Figure ganization of a classfile.

  

Magic Number

Version Number

Constant Pool

Access Flags

  

This Class

Superclass

Interfaces

Fields

  

Methods

Class/Interface Attributes

Figure 1-2. A classfile is organized into a magic number, version number, constant pool, and seven other sections

  Don’t worry about having to know this classfile architecture. I present it to satisfy the curiosities of those who are interested in learning more about how classfiles are organized. A Java program executes via a tool that loads and starts the JVM and passes the program’s main classfile to the machine. The JVM uses its classloader component to load the classfile into memory.

CHAPTER 1: Getting Started with Java

  5

  After the classfile has been loaded, the JVM’s bytecode verifier component makes sure that the classfile’s bytecode is valid and doesn’t compromise security. The verifier terminates the JVM when it finds a problem with the bytecode. Assuming that all is well with the classfile’s bytecode, the JVM’s interpreter component interprets the bytecode one instruction at a time. Interpretation consists of identifying bytecode instructions and executing equivalent native instructions.

  Note Native instructions (also known as native code) are the instructions understood by the native platform’s physical processor.

  When the interpreter learns that a sequence of bytecode instructions is executed repeatedly, it informs the JVM’s just-in-time (JIT) compiler to compile these instructions 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 instruction sequence, the program executes much faster. During execution, the interpreter might encounter a request to execute another classfile’s bytecode. When that happens, it asks the classloader to load the classfile and the bytecode verifier to verify the bytecode before executing that bytecode. Also during execution, bytecode instructions might request that the JVM open a file, display something on the screen, or perform another task that requires cooperation with the native platform. The JVM responds by transferring the request to the platform via its Java Native Interface (JNI) bridge to the native platform. Figure

  Additional Main Java Java

  Classfiles Classfile load

store

  Class Classloader

verify

Bytecode Verifier

execute

Interpreter/JIT Compiler

  Memory Java Virtual Machine Java Native Interface Calls Native Platform

  Figure 1-3. The JVM provides all of the necessary components for loading, verifying, and executing a classfile

  6

CHAPTER 1: Getting Started with Java

  The platform side of Java promotes portability by providing an abstraction over the underlying platform. As a result, the same bytecode runs unchanged on Windows, Linux, Mac OS X, and other platforms.

  

Note Java was introduced with the slogan “write once, run anywhere.” Although Java goes to great lengths

  to enforce portability (such as defining an integer always to be 32 binary digits [bits] and a long integer always to be 64 bits (see y digits), it doesn’t always succeed. For example, despite being mostly platform independent, 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 doing its best to provide a secure environment (such as the bytecode verifier) in which code executes. The goal is to prevent malicious code from corrupting the underlying platform (and possibly stealing sensitive information).

  Note Many security issues that have plagued Java have prompted Oracle to release various security

  updates. For example, blogger Brian Krebs reported on a recent update (at time of this writing) that fixes 51 security issues in his “Critical Java Update Plugs 51 Security Holes”

  

). Although troubling,

Oracle is keeping on top of this ongoing problem (whose impact on Android is minimal).

  Java SE, Java EE, and Java ME

  Developers use different editions of the Java platform to create Java programs that run on desktop computers, web browsers, web servers, mobile information devices (such as feature phones), and embedded devices (such as television set-top boxes).

   Java Platform, Standard Edition (Java SE): The Java platform for developing

applications, which are stand-alone programs that run on desktops. Java SE is

also used to develop applets, which are programs that run in web browsers.

   Java Platform, Enterprise Edition (Java EE): The Java platform for developing

  enterprise-oriented applications and servlets, which are server programs that conform to Java EE’s Servlet API. Java EE is built on top of Java SE.

   Java Platform, Micro Edition (Java ME): The Java platform for developing

MIDlets, which are programs that run on mobile information devices, and Xlets,

which are programs that run on embedded devices.

  This book largely focuses on Java SE and applications.

CHAPTER 1: Getting Started with Java

  7

  Installing the JDK and Exploring Example Applications

  The Java Runtime Environment (JRE) implements the Java SE platform and makes it possible to run Java programs. The public JRE can be downloaded from Oracle’s Java SE Downloads page at

   .

  However, the public JRE doesn’t make it possible to develop Java (and Android) applications. You need to download and install the Java SE Development Kit (JDK), which contains development tools (including the Java compiler) and a private JRE.

  

Note Oracle is also championing Java Embedded, a collection of technologies that brings Java to all kinds

  of devices (such as smartcards and vehicle navigation systems). Java SE Embedded and Java ME Embedded are the two major subsets of Java Embedded.

  Note JDK 1.0 was the first JDK to be released (in May 1995). Until JDK 6 arrived, JDK stood for Java

  Development Kit (SE wasn’t part of the title). Over the years, numerous JDKs have been released, with JDK 7 being current at time of this writing. Each JDK’s version number identifies a version of Java. For example, JDK 1.0 identifies Java 1.0, and JDK 5 identifies Java 5.0. JDK 5 was the first JDK also to provide an internal version number: 1.5.0.

  The Java SE Downloads page also provides access to the current JDK, which is JDK 7 Update 45 at time of this writing. Click the appropriate Download button to download the current JDK’s installer application for your platform. Then run this application to install the JDK. The JDK installer places the JDK in a home directory. (It can also install the public JRE in another directory.) On my Windows 7 platform, the home directory is C:\Program Files\Java\jdk1.7.0_06. (I currently use JDK 7 Update 6—I’m slow to upgrade.)

  Tip After installing the JDK, you should add the

  bin subdirectory to your platform’s PATH environment variable (see

  

  t you can execute JDK tools from any directory. Also, you might want to create a projects subdirectory of the JDK’s home directory to organize your Java projects and create a separate subdirectory within projects for each of these projects.

  8

CHAPTER 1: Getting Started with Java

  The home directory contains various files (such as README.html, which provides information about the JDK, and src.zip, which provides the standard class library source code) and subdirectories, including the following three important subdirectories:

  

  bin: This subdirectory contains assorted JDK tools. You’ll use only a few of these tools in this book, mainly javac (Java compiler) and java (Java application launcher). However, you’ll also work with jar (Java ARchive [JAR] creator, updater, and extractor—a JAR file is a ZIP file with special features), javadoc (Java documentation generator), and serialver (serial version inspector).

  

  jre: This subdirectory contains the JDK’s private copy of the JRE, which lets you run Java programs without having to download and install 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. The compiler was written in Java.

  Note

  javac isn’t the Java compiler. It’s a tool that loads and starts the JVM, identifies the compiler’s main classfile (located in tools.jar) to the JVM, and passes 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. For a quick refresher on the command line and command-line arguments topics, check out Wikipedia’s “Command-line interface” entry (

  

  The following command line shows you how to use javac to compile a source file named App.java: javac App.java The .java file extension is mandatory. The compiler complains when you omit this extension.

  Tip You can compile multiple source files by specifying an asterisk in place of the filename, as follows:

  javac *.java Assuming success, an App.class file is created. If this file describes an application, which minimally consists of a single class containing a method named main, you can run the application as follows: java App You must not specify the .class file extension. The java tool complains when .class is specified.

  In addition to downloading and installing the JDK, you’ll need to access the JDK documentation, especially to explore the Java APIs. There are two sets of documentation that you can explore.

CHAPTER 1: Getting Started with Java

  9  Oracle’s JDK 7 documentation (

  

    Google’s Java Andr

  

  

  Oracle’s JDK 7 documentation presents many APIs that are not supported by Android. Furthermore, it doesn’t cover APIs that are specific to Android. This book focuses only on core Oracle Java APIs that are also covered in Google’s documentation.

  Hello, World!

  It’s customary to start exploring a new language and its tools by writing, compiling, and running a simple application that outputs the “Hello, World!” message. This practice dates back to Brian Kernighan’s and Dennis Ritchie’s seminal book, The C Programming Language. Listing 1-1 presents the source code to a HelloWorld application that outputs this message.

  Listing 1-1. Saying Hello in a Java Language Context public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } } This short seven-line application has a lot to say about the Java language. I’ll briefly explain each feature, leaving comprehensive discussions of these features to later chapters. This source code declares a class, which you can think of as a container for describing an application. The first line, public class HelloWorld, introduces the name of the class (HelloWorld), which is preceded by reserved words (names that have meaning to the Java compiler and which you cannot use to name other things in your programs) public and class. These reserved words respectively tell the compiler that HelloWorld must be stored in a file named HelloWorld and that a class is being declared. The rest of the class declaration appears between a pair of brace characters ({}), which are familiar to C and C++ developers. Between these characters is the declaration of a single method, which you can think of as a named sequence of code. This method is named main to signify that it's the entry point into the application, and it is the analog of the main() function in C and C++.

  10

CHAPTER 1: Getting Started with Java

  The main() method includes a header that identifies this method and a block of code located between an open brace character ({) and a close brace character (}). Besides naming this method, the header provides the following information:

  

  public: This reserved word makes main() visible to the startup code that calls this method. If public wasn’t present, the compiler would output an error message stating that it couldn’t find a main() method.

  

  static: This reserved word causes this method to associate with the class instead of associating with any objects (discussed in Chapter 3) created from this class. Because the startup code that calls main() doesn’t create an object from the class to call this method, it requires that the method be declared static. Although the compiler will not report an error when static is missing, it will not be possible to run HelloWorld, which will not be an application when the proper main() method doesn’t exist.

  

  void: This reserved word indicates that the method doesn’t return a value. If you change void to a type’s reserved word (such as int) and then insert code that returns a value of this type (such as return 0;), the compiler will not report an error. However, you won’t be able to run HelloWorld because the proper main() method wouldn’t exist. (I discuss types in Chapter 2.)

  

  (String[] args): This parameter list consists of a single parameter named args, which is of type String[]. Startup code passes a sequence of command- line arguments to args, which makes these arguments available to the code that executes within main(). You’ll learn about parameters and arguments in

  main() is called with an array of strings (character sequences delimited by double quote " characters) that identify the application’s command-line arguments. These strings are stored in String-based array variable args. (I discuss method calling, arrays, and variables in Chapters 2 and 3.) Although the array variable is named args, there’s nothing special about this name. You could choose another name for this variable. main() presents a single line of code, System.out.println("Hello, World!");, which is responsible for outputting Hello, World! in the command window from where HelloWorld is run. From left to right, this method call accomplishes the following tasks:

   System identifies a standard class of system utilities. 

  out identifies an object variable located in System whose methods let you output values of various types optionally followed by a newline (also known as line feed) character to the standard output stream. (In reality, a platform-dependent line terminator sequence is output. On Windows platforms, this sequence consists of a carriage return character [integer value 13] followed by a line feed character [integer value 10]. On Linux platforms, this sequence consists of a line feed character. On Mac OS X systems, this sequence consists of a carriage return character. It's convenient to refer to this sequence as a newline.)

  

  println identifies a method that prints its "Hello, World!" argument (the starting and ending double quote characters are not written; these characters delimit but are not part of the string) followed by a newline to the standard output stream.

CHAPTER 1: Getting Started with Java

  11 Note The standard output stream is part of Standard I/O ( which also consists of standard input and standard error streams, and which

  originated with the Unix operating system. Standard I/O 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 stream, which defaults to the keyboard but can be redirected to a file. Text is written to the standard output stream, which defaults to the screen but can be redirected to a file. Error message text is written to the standard error stream, which defaults to the screen but can be redirected to a file that differs from the standard output file.

  Assuming that you’re familiar with your platform’s command-line interface and are at the command line, make HelloWorld your current directory and copy Listing 1-1 to a file named HelloWorld.java. Then compile this source file via the following command line: javac HelloWorld.java Assuming that you’ve included the .java extension, which is required by javac, and that HelloWorld.java compiles, you should discover a file named HelloWorld.class in the current directory. Run this application via the following command line: java HelloWorld If all goes well, you should see the following line of output on the screen: Hello, World! You can redirect this output to a file by specifying the greater than angle bracket (>) followed by a filename. For example, the following command line stores the output in a file named hello.txt: java HelloWorld >hello.txt

  DumpArgs

  In the previous example, I pointed out main()’s (String[] args) parameter list, which consists of a single parameter named args. This parameter stores an array (think sequence of values) of arguments passed to the application on the command line. Listing 1-2 presents the source code to a DumpArgs application that outputs each argument.

  Listing 1-2. Dumping Command-Line Arguments Stored in main()’s args Array to the Standard Output Stream public class DumpArgs { public static void main(String[] args) { System.out.println("Passed arguments:"); for (int i = 0; i < args.length; i++)

  12

CHAPTER 1: Getting Started with Java

  System.out.println(args[i]); } } Listing 1-2’s DumpArgs application consists of a class named DumpArgs that’s very similar to Listing 1-1’s HelloWorld class. The essential difference between these classes is the for loop (a construct for repeated execution and starting with reserved word for) that accesses each array item and dumps it to the standard output stream.

  The for loop first initializes integer variable i to 0. This variable keeps track of how far the loop has progressed (the loop must end at some point), and it also identifies one of the entries in the args array. Next, i is compared with args.length, which records the number of entries in the array. The loop ends when i’s value equals the value of args.length. (I discuss .length in Chapter 2.) Each loop iteration executes System.out.println(args[i]);. The string stored in the ith entry of the args array is accessed and then output to the standard output stream—the first entry is located at index (location) 0. The last entry is stored at index args.length - 1. Finally, i is incremented by 1 via i++, and i < args.length is reevaluated to determine whether the loop continues or ends.

  Assuming that you’re familiar with your platform’s command-line interface and that you are at the command line, make DumpArgs your current directory and copy Listing 1-2 to a file named DumpArgs .java. Then compile this source file via the following command line: javac DumpArgs.java Assuming that that you’ve included the .java extension, which is required by javac, and that DumpArgs.java compiles, you should discover a file named DumpArgs.class in the current directory. Run this application via the following command line: java DumpArgs If all goes well, you should see the following line of output on the screen: Passed arguments: For more interesting output, you’ll need to pass command-line arguments to DumpArgs. For example, execute the following command line, which specifies Curly, Moe, and Larry as three arguments to pass to DumpArgs: java DumpArgs Curly Moe Larry This time, you should see the following expanded output on the screen: Passed arguments: Curly Moe Larry

CHAPTER 1: Getting Started with Java

  13

  You can redirect this output to a file. For example, the following command line stores the DumpArgs application’s output in a file named out.txt: java DumpArgs Curly Moe Larry >out.txt

  EchoText

  The previous two examples introduced you to a few Java language features, and they also showed outputting text to the standard output stream, which defaults to the screen but can be redirected to a file. In the final example (see Listing 1-3), I introduce more language features and demonstrate inputting text from the standard input stream and outputting text to the standard error stream.

  Listing 1-3. Echoing Text Read from Standard Input to Standard Output public class EchoText { public static void main(String[] args) { boolean isRedirect = false; if (args.length != 0) isRedirect = true; int ch; try { while ((ch = System.in.read()) != ((isRedirect) ? -1 : '\n')) System.out.print((char) ch); } catch (java.io.IOException ioe) { System.err.println("I/O error"); } System.out.println(); } } EchoText is a more complex application than HelloWorld or DumpArgs. Its main() method first declares a Boolean (true/false) variable named isRedirect that tells this application whether input originates from the keyboard (isRedirect is false) or a file (isRedirect is true). The application defaults to assuming that input originates from the keyboard. There’s no easy way to determine if standard input has been redirected, and so the application requires that the user tell it if this is the case by specifying one or more command-line arguments. The if decision (a construct for making decisions and starting with reserved word if) evaluates args. length != 0, assigning true to isRedirect when this Boolean expression evaluates to true (at least one command-line argument has been specified). main() now introduces the int variable ch to store the integer representation of each character read from standard input. (You’ll learn about int and integer in Chapter 2.) It then enters a sequence of code prefixed by the reserved word try and surrounded by brace characters. Code within this block may throw an exception (an object describing a problem) and the subsequent catch block will handle it (to address the problem). (I discuss exceptions in Chapter 5.)

  14

CHAPTER 1: Getting Started with Java

  The try block consists of a while loop (a construct for repeated execution and starting with the reserved word while) that reads and echoes characters. The loop first calls System.in.read() to read a character and assign its integer value to ch. The loop ends when this value equals -1 (no more input data is available from a file; standard input was redirected) or '\n' (the newline/line feed character has been read, which is the case when standard input wasn’t redirected.) '\n' is an example of a character literal, which is discussed in Chapter 2.