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 Contents .................................................................................................................... vi About the Authors ................................................................................................... xvi About the Technical Reviewers ............................................................................ xviii Acknowledgments .................................................................................................. xix Introduction ............................................................................................................ xxi Chapter 1: Getting Started with Java 7 .....................................................................1 Chapter 2: Strings ....................................................................................................25 Chapter 3: Numbers and Dates ................................................................................43 Chapter 4: Data Structures, Conditionals, and Iteration ..........................................73 Chapter 5: Input and Output ..................................................................................105 Chapter 6: Exceptions and Logging .......................................................................127 Chapter 7: Object-Oriented Java ...........................................................................145 Chapter 8: Concurrency .........................................................................................185 Chapter 9: Debugging and Unit Testing .................................................................213 Chapter 10: Unicode, Internationalization, and Currency Codes ...........................237 Chapter 11: Working with Databases ....................................................................259 Chapter 12: Java 2D Graphics ...............................................................................321 Chapter 13: Java3D ...............................................................................................397 Chapter 14: Swing API ...........................................................................................413 Chapter 15: JavaFX Fundamentals ........................................................................513 Chapter 16: Graphics with JavaFX ........................................................................579 iv ■ CONTENTS AT A GLANCE Chapter 17: Media with JavaFX .............................................................................621 Chapter 18: Working with Servlets and Applets ....................................................651 Chapter 19: Intro to Android ..................................................................................707 Chapter 20: JavaFX on the Web .............................................................................745 Chapter 21: E-mail .................................................................................................779 Chapter 22: XML Processing..................................................................................787 Chapter 23: Networking .........................................................................................805 Index ......................................................................................................................823 v Introduction The Java programming language was first introduced in 1995 by Sun Microsystems. Derived from languages such as C and C++, Java was designed to be moreintuitive and easier to use than older languages, specifically due to its simplistic object model and automated facilities such as memory management. At the time, Java drew the interest of developers because of its object-oriented, concurrent architecture; excellent security and scalability; and because applications developed in the Java language could be run on any operating system that contained a Java Virtual Machine (JVM). Since its inception, Java has been described as a language that allows developers to “write once, run everywhere” as code is compiled into class files that contain bytecode, and the resulting class files can run on any compliant JVM. This concept made Java an immediate success for desktop development, which later branched off into different technological solutions over the years, including development of web-based applications and rich Internet applications (RIAs). Today, Java is deployed on a broad range of devices including mobile phones, printers, medical devices, blue ray players, and so on. The Java platform consists of a hierarchy of components, starting with the Java Development Kit (JDK), which is composed of the Java Runtime Environment (JRE), the Java programming language, and platform tools that are necessary to develop and run Java applications. The JRE contains the Java Virtual Machine (JVM), plus the Java application programming interfaces (APIs) and libraries that assist in the development of Java applications. The JVMis the base upon which compiled Java class files run and is responsible for interpreting compiled Java classes and executing the code. Every operating system that is capable of running Java code has its own version of the JVM. To that end, the JRE must be installed on any system that will be running local Java desktop or stand-alone Java applications. Oracle provides JRE implementations for most of the major operating systems, most recently adding Mac OS X to the list. Each operating system can have its own flavor of the JRE. For instance, mobile devices can run a scaled down version of the full JRE that is optimized to run Java Mobile Edition (ME) applications. The Java platform APIsand libraries are a collection of predefined classes that are used by all Java applications. Any application that runs on the JVM makes use of the Java platform APIs and libraries. This allows applications to make use of functionality that has been predefined and loaded into the JVM and leaves developers with more time to worry about the details of their specific application. The classes that comprise the Java platform APIs and libraries allow Java applications to use one set of classes in order to communicate with the underlying operating system. As such, the Java platform takes care of interpreting the set of instructions provided by a Java application into operating system commands that are required for the machine on which the application is being executed. This creates a façade for Java developers to write code against so that they can develop applications; which can be written once and ran on every machine that contains a relevant JVM. The JVM and the Java platform APIs and libraries play key roles in the lifecycle of every Java application. Entire books have been written to explore the platform and JVM. This book will focus on the Java language itself, which is used to develop Java applications, although the JVM and Java platform APIs and libraries will be referenced as needed. The Java language is a robust, secure, and modern object- oriented language that can be used to develop applications to run on the JVM. The Java programming language has been refined over several iterations and it becomes more powerful, secure, and modern with each new release. This book covers many features of the Java programming language from those that were introduced in Java 1.0 through those that made their way to the language in Java 7. In 2011, xxi ■ INTRODUCTION Oracle Corporation released Java 7, which was a milestone release for the Java ecosystem. Not only is Java 7 the most modern, statically typed, object-oriented language available for development, it also enhances the ability to integrate different languages that run on the JVM, such as Jython, Groovy, JRuby, and Scala to name a handful. On the heels of the Java 7 release, Oracle also delivered JavaFX 2.0, a breakthrough in desktop application development for the JVM. JavaFX 2.0 can be used for developing rich desktop and Internet applications using the Java language, or any other language that runs on the JVM. It provides a rich set of graphical and media user interfaces to develop extraordinary visual applications. This release is a major update to the JavaFX platform, allowing applications to be written entirely in the Java language. Previous releases of JavaFX mandated the use of JavaFX Script for development of user interfaces for JavaFX. JavaFX 2.0 does away with the mandate for using JavaFX Script and allows developers to use the language of their choice for working with the JavaFX application programming interfaces. This book covers fundamentals of Java development such as installation of the JDK, writing classes, and running applications.It delves into essential topics such as the development of object-oriented constructs, exception handling, unit testing, and localization. The book also provides solutions for desktop application development using the Swing API, and web-based solutions including servlets and applets. It covers JavaFX 2.0 in depth and is an essential guide for developers beginning to use JavaFX.This book can be used as a guide for solving problems that ordinary Java developers may encounter at some point. A broad range of topics is discussed, and the solutions to the problems that are covered in this book are concise and tothe point. If you are a novice Java developer, we hope that this book will help you get started on your journey to working with one of the most advanced and widely used programming languages available today. For those of you who have used the Java language for some time, we hope that this book will provide you with updated material that is new to Java 7 and JavaFX 2.0 so that you can further refine your Java development skills. We ensure that advanced Java application developers will also learn a thing or two regarding the new features of the language and perhaps even stumble upon some techniques that were not used in the past. Whatever your skill level, this book will be good to have close at hand as a reference for solutions to those problems that you will encounter in your daily programming. Who This Book Is For This book is intended for all those who are interested in learning the Java programming language and/or already know the language but would like some information regarding the new features included in Java SE 7 and JavaFX 2.0. Those who have not yet programmed in the Java language can read this book, and it will allow them to start from scratch to get up and running quickly. Intermediate and advanced Java developers who are looking to update their arsenal with the latest features that Java SE 7 and JavaFX 2.0 make available to them can also read the book to quickly update and refresh their skill set. Java desktop programmers will find this book useful for its content on developing desktop applications using the Java Swing toolkit and JavaFX 2.0. Developers of Java web applications will find useful content regarding servlets, applets, and more. There is, of course, a myriad of other essential topics that will be useful to Java developers of any type. How This Book Is Structured This book is structured so that it does not have to be read from cover to cover. In fact, it is structured so that developers can chose which topic(s) they’d like to read about and jump right to them. Each recipe contains a problem to solve, one or more solutions to solve that problem, and a detailed explanation of how the solution works. Although some recipes may build upon concepts that have been discussed in other recipes, they will contain the appropriate references so that the developer can find other related recipes that are beneficial to the solution. The book is designed to allow developers to get up and running quickly with a solution so that they can be home in time for dinner. xxii C H A P T E R 1 ■■■ Getting Started with Java 7 The Java language has been around for quite some time now. It has been labeled a “legacy language,” and some say that Java will become outdated and a language of the past. Those who advocate languages that do not run on the Java Virtual Machine (JVM) make these statements, and they are untrue. With each release, the Java language gains new features, adding new capabilities to help developers of the JVM become more productive. The first major release of Java was distributed in 1996, and since then the language has undergone many changes. Over the years, the language has added features such as inner classes, JavaBeans, regular expressions, generics, enumerations, and so on. With each release, the Java language changes the way in which applications are built and used. The last major update of Java was Java 1.6 (Java 6 Tiger), which was released in late 2006. That release featured updates that offered new features to the Java language, as well as other languages on the JVM. Scripting language support with JSR223 paved the road for integration between Java and other languages to integrate with one another. The Java 7 release marks one of the most monumental updates to the language in years. Not only does Java 7 offer more features but it also enhances the ability to write other languages for the JVM. Constructs such as the try-with-resources and the diamond operator add productivity to the language. Invoke Dynamic increases the language’s ability to offer support for dynamic languages. The new I/O library enhances platform independence and makes I/O easier to use. New graphics features have been added along with new Swing components to make graphical user interfaces (GUIs) better. All these features and more offer one of the largest updates to the Java language in years. The language is better than ever, and it has a user community that rivals any other. This chapter will introduce newcomers to the Java language. It will help those who are unfamiliar with the language to get started. You will learn how to install Java and configure it for your environment. You will learn basics of Java such as how to create a class and how to accept keyboard input. Documentation is often overlooked, but in this chapter you will quickly learn how to create great documentation for your Java code. In the end, you will quickly get up and started developing with Java 7. 1-1. Downloading and Installing Java 7 Problem You want to install the Java 7 Development Kit (JDK 7) on your computer workstation or laptop. 1 CHAPTER 1 ■ GETTING STARTED WITH JAVA 7 Solution Download the requisite Java 7 distribution for your platform, or download and build OpenJDK. Once downloaded and/or built, run installation scripts as necessary. To download the binary distribution of the JDK, please visit the Oracle downloads page and choose the correct binary Java SE release for your platform of choice. Note If you are working on Mac OS X, you have a couple of options for working with OpenJDK. To download sources for OpenJDK, please visit http://openjdk.java.net and build the sources on your workstation or laptop, or go to the Google Source project openjdk-osx-build and download an installer. How It Works The JDK is distributed in a binary format via the Oracle Corporation. If interested in obtaining the most recent build of the latest JDK, go to the OpenJDK site, download, and build the sources. Since the binary installer contains an installation wizard, I will not cover the wizard installation in detail. However, there are a few key things to note regarding the installation process. Be sure that you download the JDK and not the Java Runtime Environment (JRE) because you will want to develop with Java. The JRE does not include the tools that are required to develop and compile Java code. Instead, the JRE merely provides the runtime required to load and execute Java applications on the JVM. When you initiate the installation wizard, you will be presented with a number of different features that can be installed. Specifically, you will be given the choice to install Development Tools, Demos and Samples, and Source Code. I recommend installing everything because you will benefit from looking at the demos and samples, and you may also benefit from looking at the JDK sources. You can specify a default installation location for the JDK. By default, the wizard will want to install to the Program Files area on a Windows machine. I recommend changing this location to another directory that contains no spaces in its name and is made at the root of your OS drive. This will alleviate CLASSPATH issues in the future. I recommend installing to C:\Java\jdk1.7.0 on a Windows machine. If you have multiple drives, you can install to any of them, although it is not recommended to install the JDK on an external drive. On all platforms, you can have more than one JDK installed. This allows you to run older Java programs that rely on deprecated or removed Java tools, and at the same time provides the ability to work with the most recent Java platform. Hence, it is a smart choice to install the JDK into a directory containing the JDK release number. In our case, we are installing into the directory jdk1.7.0. If you are working on a Solaris or Linux platform, you will have the same type of wizard that is provided for use with Microsoft Windows. However, if you are working on a Mac OS X platform, you may not be provided with such a wizard. The JDK 7 Developer Preview from Oracle is bundled as a disk image, and the installation involves opening the disk image and dragging the JDK bundle to the designated location within the OS. You also have the option of going to the OpenJDK site and downloading the sources so that they can be built and installed on your operating system. There is also a dmg (disk image) available for the latest builds of OpenJDK for OS X hosted on the Google Code repository. Since this is the easier route to take, we choose to install from the disk image. Go to the openjdk-osx-build project on Google Code (http://code.google.com/p/openjdk-osx- build/) and download the most recent OpenJDK disk image. You will want to install the universal disk image if it is available. Once downloaded, you can open the disk image, and run the Installation.pkg 2 CHAPTER1 ■ GETTING STARTED WITH JAVA 7 file. Once you run the installer, a standard OS X installation wizard will begin. Unlike the Microsoft Windows installation wizard, you cannot select the installation path. Once the installation completes, you can go to the Java Preferences utility and see the OpenJDK 7 listed as one of the options. Drag it to the top of the list to ensure that Java 7 will be the default runtime. Note If you are running Java applications that are not compatible with Java 7 on OS X, you can use the Java Preferences utility to drag the JDK of your choice to the top of the list of available JDK installations to set as default. 1-2. Configuring the CLASSPATH Problem You want to execute a Java program or include an external Java library in the application you are executing. Note Would you like to run a “Hello, World” program now that you’ve installed the JDK as described in the previous recipe? Not to worry. That’s the very next recipe. First though, you should configure your CLASSPATH. Solution Set the CLASSPATH equal to the directory location of the user-defined Java classes or Java Archive (JAR) files that you need to have access to for executing your application. Note It is a good idea to organize your code; it is also good to organize where you place your code on the computer. A good practice is to place all your Java projects within the same directory; it can become your workspace. Place all the Java libraries that are contained in JAR files into the same directory for easier management. 3 CHAPTER 1 ■ GETTING STARTED WITH JAVA 7 Let’s say that you have a directory named JAVA_DEV located at the root of your OS drive, and all the files that you need to have access to are located in this directory. If this is the case then you would do the following at the command line or terminal: • Setting CLASSPATH on a Microsoft Windows platform: set CLASSPATH=C:\JAVA_DEV\some-jar.jar • Setting CLASSPATH on a UNIX platform: export CLASSPATH=/JAVA_DEV/some-jar.jar Alternately, the javac tool provides an option for specifying resources that need to be loaded for an application. On all platforms, setting the CLASSPATH using this technique can be done as follows: javac –classpath /JAVA_DEV/some-jar.jar Of course, on Microsoft Windows machines the file path will use the backslash (\) instead. How It Works In order for the JVM to find the resources that are needed to execute Java applications, there needs to be a specified search path that can be used to find associated files. That being said, the CLASSPATH can be used by the JVM in order to find and load any Java sources or JAR files that may be required. The CLASSPATH is a parameter that tells the JVM where to look for classes and packages, and it can be set using an environment variable or command-line argument. When executing Java programs, the JVM finds and loads classes as needed using the following search order: • The classes that are fundamental to the Java Platform and are contained in the Java installation directory • Any packages or JAR files that are located within the extension directory of the JDK • Packages, classes, JAR files, and libraries that are loaded somewhere on the specified CLASSPATH Note JAR files are a used to package applications and Java libraries into a distributable format. 4
Description: