Chapter    1

Getting Started With Java

Android is Google’s software stack for mobile devices. This stack consists of applications (or apps as they are commonly called), a virtual machine (software-based processor and associated environment) in which apps run, middleware (software that sits on top of the operating system and provides various services to the virtual machine and its apps), and a Linux-based operating system.

Android apps are written in Java and use various Java Application Program Interfaces (APIs). Because you will 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 app development. It provides you with the fundamentals of the Java language 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.

An API refers to an interface that an application’s code uses to communicate with other code, which is typically stored in some kind of software library. For more information on this term, check out Wikipedia’s “Application programming interface” topic (http://en.wikipedia.org/wiki/Application_programming_interface).

This chapter sets the stage for teaching you the essential Java concepts that you need to understand before you embark on your Android app development career. I first answer the “What is Java?” question. I next show you how to install the Java SE Development Kit (JDK), and introduce you to JDK tools for compiling and running Java applications.

After showing 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 provide you with a high-level overview of various Java APIs that you can access from your Java applications and Android apps. In subsequent chapters, you’ll explore these and other useful APIs in greater detail.

Note   Chapter 1 is short but intense, presenting many concepts that you’ll encounter in more detail throughout this book. If you are new to Java, you might find yourself a little overwhelmed by these concepts. However, any fog should clear as you progress through remaining chapters. If you still feel somewhat confused, please contact me ([email protected]) with your questions and I’ll do my best to help you.

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 also briefly explores each of these editions, along with Android.

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, and a version of Unix; and Oak, a language developed by James Gosling for writing applications to run on Star7, which 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. Check out http://oracle.com/technetwork/java/index.html 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 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 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, and 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.

The following list identifies a few differences between Java and C/C++:

  • Java supports an additional comment style known as Javadoc. (I briefly introduce Javadoc in Chapter 2.)
  • 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 type (see http://en.wikipedia.org/wiki/Integer_(computer_science)); 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 will not find in C/C++.

You will learn about single-line and multiline comments in Chapter 2. Also, you will learn about reserved words, primitive types, operators, blocks, and statements (including labeled break and 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 (variables containing addresses—see http://en.wikipedia.org/wiki/Pointer_(computer_programming)).

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 while (x) x++; (assume that x is an integer-based variable initialized to 0—I discuss variables in Chapter 2) where x++ adds 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), 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.

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. The execution environment consists of libraries for running programs and interacting with the underlying operating system.

The execution environment includes a huge library of prebuilt classfiles that perform common tasks, such as math operations (e.g., trigonometry) 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 instructions (and associated data) that are executed by the virtual machine. These instructions are known 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 equivalent of classes, a language feature discussed in Chapter 3.

A Java program executes via a tool (e.g., java) that loads and starts the virtual machine and passes the program’s main classfile to the machine. The virtual machine uses a classloader (a virtual machine or execution environment component) to load the classfile.

After the classfile has been loaded, the virtual machine’s bytecode verifier component makes sure that the classfile’s bytecode is valid and doesn’t compromise security. The verifier 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 interpreter 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 underlying platform’s physical processor.

When the interpreter learns that a sequence of bytecode instructions is executed repeatedly, it informs the virtual machine’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 prior to executing that bytecode.

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-based, Linux-based, Mac OS X-based, and other platforms.

Note   Java was introduced with the slogan “write once, run anywhere.” Although Java goes to great lengths to enforce portability (e.g., an integer is always 32 binary digits [bits] and a long integer is always 64 bits—see http://en.wikipedia.org/wiki/Bit to learn about binary digits), it doesn’t always succeed. For example, despite being mostly platform independent, certain parts of Java (e.g., the scheduling of threads, discussed in Chapter 8) vary from underlying platform to underlying platform.

The platform side of Java also promotes security by providing a secure environment (e.g., the bytecode verifier) in which code executes. The goal is to prevent malicious code from corrupting the underlying platform (and possibly stealing sensitive information).

Java SE, Java EE, Java ME, and Android

Developers use different editions of the Java platform to create Java programs that run on desktop computers, web browsers, web servers, mobile information devices (e.g., feature phones), and embedded devices (e.g., 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.

Developers also use a special Google-created edition of the Java platform (see http://developer.android.com/index.html) to create Android apps that run on Android-enabled devices. This edition is known as the Android platform.

Google’s Android platform presents a Dalvik virtual machine that runs on top of a specially modified Linux kernel. An Android app’s Java source code is compiled into Java classfiles, which are then translated into a special file for Dalvik to execute.

Note   Learn more about the Android OS via Wikipedia’s “Android (operating system)” entry (http://en.wikipedia.org/wiki/Android_(operating_system)) and about the Dalvik virtual machine via Wikipedia’s “Dalvik (software)” entry (http://en.wikipedia.org/wiki/Dalvik_(software)).

In this book, I cover the Java language (supported by Java SE and Android) and various Java SE APIs that are also supported by Android. I focus on language features through Java version 5 and on Java APIs through Java 5, with a small amount of Java 6.

Note   Google’s Android platform is based on an open source release of Java 5. It doesn’t officially recognize language features newer than Java 5, although it’s possible to add this support (see www.informit.com/articles/article.aspx?p=1966024). Regarding APIs, this platform supports APIs from Java 6 and previous Java versions. Also, it provides its own unique APIs.

Installing and Exploring the JDK

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 (http://oracle.com/technetwork/java/javase/downloads/index.html).

However, the public JRE doesn’t make it possible to develop Java programs. For that task, 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   JDK 1.0 was the first JDK to be released (in May 1995). Until JDK 6 arrived, JDK stood for Java Development Kit (SE was not part of the title). Over the years, numerous JDKs have been released, with JDK 7 being current at time of 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 to also provide an internal version number: 1.5.0.

Google doesn’t provide a JDK. What it does provide is similar to a JRE, but with an Android focus.

The Java SE Downloads page also provides access to the current JDK, which is JDK 7 Update 9 at time of writing. Click the Download JDK link (on the page at http://oracle.com/technetwork/java/javase/downloads/index.html) to download the current JDK’s installer program for your platform.

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 FilesJavajdk1.7.0_06. (I currently use JDK 7 Update 6.)

Tip   After installing the JDK, you should add the bin subdirectory to your platform’s PATH environment variable (see http://java.com/en/download/help/path.xml) so 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.

The home directory contains various files (e.g., 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), java (Java application launcher), jar (Java archive creator, updater, and extractor), and javadoc (Java documentation generator).
  • 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 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, 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. You can 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’re ready to explore a small DumpArgs application that outputs its command-line arguments to the standard output stream.

Note   The standard output stream is part of Standard I/O (http://en.wikipedia.org/wiki/Standard_streams), 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.

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 Stream

public 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 method within this class named main(), which is the application’s entry point and provides the code to execute. (You will learn about classes and methods in Chapter 3.)

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 (}). As well as 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. (I discuss reserved words in Chapter 2.)
  • 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 DumpArgs, 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 (e.g., int) and then insert a statement that returns a value of this type (e.g., return 0;), the compiler will not report an error. However, you won’t be able to run DumpArgs 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 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 Chapter 3.

main() is called with an array of strings (character sequences) 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 is nothing special about this name. You could choose another name for this variable.

The block of code first executes System.out.println("Passed arguments:");, which calls System.out’s println() method with the "Passed arguments :" string. This string is written to the standard output stream.

From left to write, 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 character to the standard output stream; println identifies a method that prints its argument followed by a newline character to standard output; and "Passed arguments:" is a string (a sequence of characters delimited by double quote " characters and treated as a unit) that is passed as the argument to println and written to standard output (the starting " and ending " double quote characters are not written; these characters delimit but are not part of the string).

Note   System.out provides access to a family of println() methods and a family of print() methods for outputting different kinds of data (e.g., sequences of characters and integers). Unlike the println() methods, the print() methods don’t terminate the current line; subsequent output continues on the current line.

Each println() method terminates a line by outputting a line separator string, which is defined by system property line.separator, and which is not necessarily a single newline character (identified in source code via character literal ' '). (I discuss system properties in Chapter 8, line.separator in Chapter 11, and character literals in Chapter 2.) For example, on Windows platforms, 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).

The block of code next uses a for loop to repeatedly execute System.out.println(args[i]);. The loop executes args.length times, or once for each string stored in args. (I discuss for loops and .length in Chapter 2.)

The System.out.println(args[i]); method call reads the string stored in the ith entry of the args array—the first entry is located at index (location) 0; the last entry is stored at index args.length - 1. This method call then outputs this string to standard output.

Assuming that you’re familiar with your platform’s command-line interface and are at the command line, make DumpArgs your current directory and copy Listing 1-1 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

You can redirect the output destination to a file by specifying the greater than angle bracket (>) 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 specify System.err.println() to output characters to the standard error stream. (System.err provides 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 error message so that the error messages are displayed on the screen, even when standard output is redirected to a file.

Congratulations on successfully compiling your first application source file and running the application! Listing 1-2 presents the source code to a second application, which echoes text obtained from the standard input stream to the standard output stream.

Listing 1-2.  Echoing Text Read from Standard Input to Standard Output

public 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() ) !=1)
         System.out.print((char) ch);
      System.out.println();
   }
}

After outputting a message that prompts the user to enter some text, main() introduces int variable ch to store each character’s integer representation. (You will learn about int and 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 to ch. The loop ends when this value equals −1 (no more input data is available).

Note   When standard input is redirected to a file, System.in.read() reads each character from the file (which is subsequently converted to an integer) until there are no more characters to be read. At that point, this method returns −1. However, when standard input isn’t redirected, the loop doesn’t end because −1 is never seen. In this case, the end of a line of text is signified (on Windows platforms) by a carriage return character (integer value 13) followed by a line feed character (integer value 10). The exact termination sequence is platform dependent. You must press the Ctrl and C keys simultaneously on Windows (or the equivalent keys on a non-Windows platform) to terminate the loop.

For any other value in ch, this value is converted to a character via (char), which is an example of Java’s cast operator (discussed in Chapter 2). The character is then output via System.out.print(), which doesn’t also terminate the current line. The final System.out.println(); call terminates the current line without outputting any content.

Note   When standard input is redirected to a file and System.in.read() is unable to read text from the file (perhaps the file is stored on a removable storage device that has been removed prior to the read operation), System.in.read() fails by throwing an object that describes this problem. I acknowledge this possibility by appending throws java.io.IOException to the end of the main() method header. I discuss throws in Chapter 5 and java.io.IOException in Chapter 11.

Compile Listing 1-2 via javac EchoText.java and run the application via java EchoText. You’ll be prompted to enter some text. After you input this text and press Enter, the text will be sent to standard output. For example, consider the following output:

Please enter some text and press Enter!
Hello Java
Hello Java

You 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 from EchoText.java and outputs this text to the screen.

ANDROID APP ENTRY POINT

The DumpArgs and EchoText applications demonstrate public static void main(String[] args) as a Java application’s entry point. This is where the application’s execution begins. In contrast, an Android app doesn’t require this method for its entry point because the app’s architecture is very different.

Android apps are based on a federation of interacting components, which are known as activities, services, broadcast receivers, and content providers. Activities provide user interface screens, services support background processing, broadcast receivers respond to system-wide broadcasts, and content providers offer portable data access.

Consider the activity. This component is implemented as a class that inherits life cycle methods from Android’s android.app.Activity class and has the opportunity to override them. (I discuss methods in Chapter 3 and inheritance and overriding in Chapter 4.) For example, it could override the void onCreate(Bundle savedInstanceState) method to construct a user interface screen when Android calls this method.

In this book, I present Java applications with public static void main(String[] args) methods. I do so because the book’s focus is on learning Java as a preparatory step to getting into Android app development.

As well as 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:

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 Java APIs that are covered in Google’s documentation.

Installing and Exploring the Eclipse IDE

Working 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 manage without the help of an IDE.

An IDE consists of a project manager for managing a project’s files, a text editor for entering and editing source code, a debugger for locating bugs, and other features. Eclipse is a popular IDE that Google supports for developing Android apps.

Note   For convenience, I use JDK tools throughout this book, except for this section where I discuss and demonstrate the Eclipse IDE.

EclipseIDE is an open source IDE for developing programs in Java and other languages (e.g., C, COBOL, PHP, Perl, and Python). Eclipse Classic is one distribution of this IDE that is available for download; version 4.2.1 is the current version at time of writing.

You should download and install Eclipse Classic to follow along with this section’s Eclipse-oriented example. Begin by pointing your browser to www.eclipse.org/downloads/ and accomplishing the following tasks:

  1. Scroll down the page until you see an Eclipse Classic entry. (It may refer to 4.2.1 or a newer version.)
  2. Click one of the platform links (e.g., Windows 32 Bit) to the right of this entry.
  3. Select a download mirror from the subsequently displayed page and proceed to download the distribution’s archive file.

I downloaded the approximately 183 MB eclipse-SDK-4.2.1-win32-x86_64.zip archive file for my Windows 7 platform, unarchived this file, moved the resulting eclipse home directory to another location, and created a shortcut to that directory’s eclipse.exe file.

After installing Eclipse Classic, run this application. You should discover a splash screen identifying this IDE and a dialog box that lets you choose the location of a workspace for storing projects, followed by a main window like that shown in Figure 1-1.

9781430257226_Fig01-01.jpg

Figure 1-1 .  Keep the default workspace or choose another workspace

Click the OK button and you’re taken to Eclipse’s main window. See Figure 1-2.

9781430257226_Fig01-02.jpg

Figure 1-2 .  The main window initially presents a Welcome tab

The main window initially presents a Welcome tab from which you can learn more about Eclipse. Click this tab’s X icon to close this tab; you can restore the Welcome tab by selecting Welcome from the menubar’s Help menu.

The Eclipse user interface is based on a main window that consists of a menubar, a toolbar, a workbench area, and a statusbar. The workbench presents windows for organizing Eclipse projects, editing source files, viewing messages, and more.

To help you get comfortable with the Eclipse user interface, I’ll show you how to create a DumpArgs project containing a single DumpArgs.java source file with Listing 1-1’s source code. You’ll also learn how to compile and run this application.

Complete 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 the Project name text field. Keep all the other defaults and click the Finish button.

After the second step, you’ll see a workbench similar to that shown in Figure 1-3.

9781430257226_Fig01-03.jpg

Figure 1-3 .  A DumpArgs entry appears in the workbench’s Package Explorer

On the left side of the workbench, you see a window titled Package Explorer. This window identifies the workspace’s projects in terms of packages (discussed in Chapter 5). At the moment, only a single DumpArgs entry appears in this window.

Clicking the triangle icon to the left of DumpArgs expands this entry to reveal src and JRE System Library items. The src item stores the DumpArgs project’s source files, and the JRE System Library identifies various JRE files that are used to run this application.

You’ll 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 the resulting pop-up menu.
  2. In the resulting New File dialog box, enter DumpArgs.java into the File name text field, and click the Finish button.

Eclipse responds by displaying an editor window titled DumpArgs.java. Copy Listing 1-1 content to this window. Then compile and run this application by selecting Run from the Run menu. (If you see a Save and Launch dialog box, click OK to close this dialog box.) Figure 1-4 shows the results.

9781430257226_Fig01-04.jpg

Figure 1-4 .  The Console tab at the bottom of the workbench presents the DumpArgs application’s output

You must pass command-line arguments to DumpArgs to see additional output from this application. Accomplish this task as follows:

  1. Select Run Configurations from the Run menu.
  2. In the resulting Run Configurations dialog box, select the Arguments tab.
  3. Enter Curly Moe Larry into the Program arguments text area and click the 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 “Passed arguments:”.

This is all I have to say about the Eclipse IDE. For more information, study the tutorials via the Welcome tab, access IDE help via the Help menu, and explore the Eclipse documentation at www.eclipse.org/documentation/.

Overview of Java APIs

Oracle organizes its standard class library APIs into packages (see Chapter 5), which are analogous to file folders. Similarly, Google organizes its Android-oriented standard class library APIs into packages. In this section, I provide an overview of various Java APIs that are common to Oracle and Google. Furthermore, I discuss (throughout this book) only those APIs that are located in both libraries. By limiting my discussion to common APIs, I avoid discussing Java APIs that cannot be used when creating Android apps.

Language-Support and Other Language-Oriented APIs

Java relies on several APIs to support basic language features, such as strings (see Chapter 7), exceptions (see Chapter 5), and threads (see Chapter 8). For example, the java.lang package offers the String class to support strings, the Throwable class to support exceptions, and the Thread class and Runnable interface to support threads.

Java also provides APIs that fulfill language-oriented tasks. For example, java.lang offers a StringBuffer class (see Chapter 7) for creating changeable strings, a Math class (see Chapter 7) for performing trigonometric and other basic mathematics operations, and a Package class (see Chapter 7) for obtaining package-oriented information.

Collections-Oriented APIs

Java’s designers have developed a powerful Collections Framework for organizing objects (see Chapter 9). This framework, which is located in the java.util package, is based on interfaces and lets you store objects in lists, queues, sets (sorted or unsorted), and maps (sorted or unsorted). These interfaces are associated with various implementation classes (e.g., ArrayList).

The Collections Framework also offers the Collections and Arrays classes. These utility classes (classes consisting of static [class] methods) provide various methods for performing common operations on collections and arrays. For example, Collections lets you conveniently search or sort a collection; and Arrays lets you conveniently search, sort, copy, or fill an array.

Additional Utility APIs

Java’s designers have also developed a powerful Concurrency Utilities framework that offers a high-level alternative to low-level threads (see Chapter 10). This framework’s APIs are organized into java.util.concurrent, java.util.concurrent.atomic, and java.util.concurrent.locks packages. Examples of APIs in the first package include the Executor interface and the CyclicBarrier class.

Additional utility APIs that are located in the java.util package include the Date class for working with dates, the Formatter class for formatting data items (e.g., integers and strings), the Random class for achieving sophisticated random number generation, and the Scanner class for parsing an input stream of characters into integers, strings, and other values. I discuss these APIs in Chapter 10.

Finally, the java.util.zip package offers capabilities for extracting information from existing ZIP archives and creating new ZIP archives (see Chapter 10). Also, the related java.util.jar package extends java.util.zip by offering additional capabilities required by JAR files, specifically, reading attributes from and writing attributes to the JAR file’s manifest (see Chapter 10).

Classic I/O APIs

The ability to input and output information has always been important to Java. You’ve already discovered Standard I/O, but there is much more to explore in Chapter 11. For example, the java.io package offers the File class for performing file-oriented operations (e.g., listing a directory’s files), and also offers stream/writer/reader classes for performing I/O (typically involving files).

Networking APIs

Although much I/O takes place in the context of a filesystem, Java also offers the ability to perform I/O over a network via the various types located in its java.net package (see Chapter 12). For example, you can use the Socket and ServerSocket classes to create the client and server ends of a network communication link.

Socket offers a low-level approach to communicating over a network. In some cases, you’ll use the higher-level URL class to communicate over the Web, perhaps to obtain a web page. As you interact with the Web, you’ll encounter cookies that you can manage via additional java.net interfaces and classes, such as CookiePolicy and CookieManager.

New I/O APIs

Modern operating systems have introduced sophisticated I/O mechanisms such as memory-mapped files and readiness selection. Java supports these new I/O mechanisms via Buffer, Channel, Selector, and related types found in java.nio and related packages. Also, java.util.regex supports new I/O by offering high-performance string operations. See Chapter 13.

Database APIs

Databases store information, and relational databases store this information in tables that can be related to each other via special key columns. Java supports database access via the java.sql and javax.sql packages. The former package includes classes and interfaces such as DriverManager and ResultSet; the latter package offers DataSource, RowSet, and more. See Chapter 14.

EXERCISES

The following exercises are designed to test your understanding of Chapter 1’s content:

  1. What is Java?
  2. What is a virtual machine?
  3. What is the purpose of the Java compiler?
  4. True or false: A classfile’s instructions are commonly referred to as bytecode.
  5. What does the virtual machine’s interpreter do when it learns that a sequence of bytecode instructions is being executed repeatedly?
  6. How does the Java platform promote portability?
  7. How does the Java platform promote security?
  8. True or false: Java SE is the Java platform for developing servlets.
  9. What is the JRE?
  10. What is the difference between the public and private JREs?
  11. What is the JDK?
  12. Which JDK tool is used to compile Java source code?
  13. Which JDK tool is used to run Java applications?
  14. What is Standard I/O?
  15. How do you specify the main() method’s header?
  16. What is an IDE? Identify the IDE that Google supports for developing Android apps.

Summary

Java is a language and a platform. The language is partly patterned after the C and C++ languages to shorten the learning curve for C/C++ developers. The platform consists of a virtual machine and associated execution environment.

Developers use different editions of the Java platform to create Java programs that run on desktop computers, web browsers, web servers, mobile information devices, and embedded devices. These editions are known as Java SE, Java EE, and Java ME.

Developers also use a special Google-created edition of the Java platform to create Android apps that run on Android-enabled devices. This edition, known as the Android platform, presents a Dalvik virtual machine that runs on top of a specially modified Linux kernel.

The public JRE implements the Java SE platform and makes it possible to run Java programs. The JDK provides tools (including the Java compiler) for developing Java programs and also includes a private copy of the JRE.

Working with the JDK’s tools at the command line is not recommended for large projects, which are hard to manage without the help of an integrated development environment. Eclipse is a popular IDE that Google supports for developing Android apps.

Oracle organizes its standard class library APIs into packages, which are analogous to file folders. Similarly, Google organizes its Android-oriented standard class library APIs into packages. In this chapter I also presented an overview of some of these packaged APIs.

Chapter 2 starts to introduce you to the Java language by focusing on this language’s fundamentals. You’ll learn about comments, identifiers, types, variables, expressions, statements, and more.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.216.249