返回列表 发帖

《Java 2 Primer Plus》


Java Primer Plus guides the reader through the Java programming language from the basic concepts (basic syntax, variable, literals, operators, loops, conditional statements, etc.) through advanced topics (RMI, JDBC, Network socket programming, etc.). It provides a deep explanation of Java programming concepts and technologies using classroom tested and proven techniques. What makes this book unique is that it spends the last part showing the reader how to integrate Java technologies into everyday Web related practices and with other technologies.


《Java 2 Primer Plus》

Introduction
Java programming, like all computer programming, requires a dedication to learning and the right study tools. As a Java programmer, I have spent years reading various books on every aspect of Java and analyzing Sun';s implementation of it to gain insight into its design philosophies. The Java programming books I have read vary in detail and approach, but something very important is missing.
Several years back, when I was deep into Windows programming, I read Don Box';s Essential COM, which changed my standards for programming books. COM is a difficult subject to understand, let alone master, but Don';s approach was quite different from any other book on the market. He started from the foundation and derived COM feature-by-feature so that the reader truly understood why each design decision was made. By the end of the first chapter I looked at COM from a completely different perspective: It was no longer a crazy mystery, but everything suddenly made sense. Then, when learning the more advanced features of the language, it was just adding details to build on a firmly established foundation.
I have not read a Java book that has taken this approach, which is what differentiates Java 2 Primer Plus from any other book. Instead of simply teaching the reader how to write Java programs, every effort has been made to teach the reader why the language is the way it is. The book also explores the underlying design decisions Java';s originators made when creating the language. The goal, therefore, is for the reader to walk away from this book with a solid foundation in the Java programming language so, as new technologies evolve, the reader can easily add the details to his firmly established foundation.
Who Should Read This Book?
Java 2 Primer Plus is geared to the following categories of readers:
Readers new to computer programming
Existing programmers new to Java
Java programmers wanting to gain a deeper understanding of Java
This book starts from the foundation of Java and assumes nothing about the reader. It offers sufficient depth to appeal to both the novice and the seasoned pro. If you are already proficient in another programming language, your focus in the early chapters will be on the specific application of familiar concepts in the Java programming language. If you are new to computer programming in general, the book will guide you through the basic concepts and explain how they are derived.
This book was built not only from my experience as a professional Java programmer, but also from tried-and-true instructional techniques borrowed from the classroom. I have taught a wide variety of students ranging from new computer programmers to Visual Basic experts; from accountants to experienced Java programmers, and have engineered an approach to Java programming that has worked in each specific case. My goal is to transfer this experience to print.
What You Need to Know Before Reading This Book
You do not need to have any programming background to find this book a valuable study aid.
How This Book Is Organized
This book is broken down into five parts:
Part I: Java Foundation
Part II: Object-Oriented Programming
Part III: Graphical User Interfaces
Part IV: Advanced Topics
Part V: Web Technologies
Part I, "Java Foundation," covers the basics of computer programming as applied to Java programming. It talks about Java';s keywords, data types, variables, operators, flow-control, and methods. After reading through Java Foundations, you will understand the major tools you will use to build Java programs later in the book.
Part II, "Object-Oriented Programming," introduces you to the most popular and effective programming paradigm ever seen in computer programming: object-oriented programming. It talks about Java classes, encapsulation, inheritance, and polymorphism. Furthermore, it includes some of the more advanced core features of Java, including interfaces, exception handling, Java';s collection classes, and input and output.
Part III, "Graphical User Interfaces," teaches you how to build graphical user interfaces, which are targeted for both applications and applets, using the standard Abstract Window Toolkit as well as advanced user interfaces using Swing. It walks you through a complete derivation of the event-delegation model that drives Java';s entire event-handling strategy.
Part IV, "Advanced Topics," brings together the advanced topics that complete what I call the core components of the Java programming language. After this section you should be able to understand any application of Java whether it be applied to the Web, enterprise computing, or mobile computing. The topics include multithreaded programming, Java';s introspection and reflection programming interface, the Java Database Connectivity API (JDBC), network programming using raw sockets, and Java';s Remote Method Invocation (RMI). The section finishes up with a discussion of best practices and code optimization techniques.
Part V, "Web Technologies," discusses the application of the Java programming language in server-side Web programming. It discusses the modest beginnings of servlets, the more recent and easy-to-use JavaServer Pages (JSP), as well as advanced subjects such as building custom tag libraries to supplement your Web programming and handling XML. Finally, it includes a discussion into proper Web application design and the application of the tried-and-true Model-View-Controller (MVC) design pattern applied to Web design. Because Java Web programming is very flexible, its technology can easily be abused and not yield optimal results; this section addresses the need to ensure that your Web applications are scalable and optimally configured.

TOP

《Java 2 Primer Plus》

Part I: Java Foundation
  1 Introduction to Java

  2 Keywords, Data Types, and Variables

  3 Operators

  4 Flow Control

  5 Methods


Chapter 1. Introduction to Java
You will learn about the following in this chapter:
What is Java?
Setting up a Java programming environment
Writing your first Java program
Welcome to Java!
This chapter will take you through a brief introduction to the Java language, including all the benefits of the language and answer the question: Why would you want to use Java? It will talk a little about Java';s history, and then get you up and running with your first Java application!
What Is Java?
Java is a high-level programming language that has many functions. It is used to develop applets that reside on Web pages, applications that run on your desktop, server-side middleware that are used to communicate between clients and server resources. Java is also used on Web servers and in embedded systems and smart devices, just to name a few of its many functions. The practical applications of Java can be found in Web browser applets and in server-side applications (Web and enterprise-wide).
History
The following is a short history of the Java programming language and the reasons for its inception. In 1991, a research group working as part of Sun Microsystems';s "Green" project, was developing software to control consumer electronic devices. The goal was to develop a programming language that could be used to control and network "smart" devices, such as televisions, toasters, and even buildings. These devices would all coexist and communicate with one another.
The first prototype that Sun came out with was a device called the Star7—a device, similar to a remote control, that could communicate with other Star7 devices. The initial intent was to use C++ to control the Star7, but as a result of frustration with that language, Green project member James Gosling developed a new language called Oak to control the Star7. The title Oak came from a tree that Gosling could see from his office window while developing the language. Sun later replaced the name with Java because Oak was already being used.
As a result of Oak, or Java, being designed to run on small appliances, the language had the following inherent benefits:
It was small, so it could run on the limited memory of small appliances.
It was efficient and reliable, so it could function as a small appliance—we are all used to computer crashes, but a microwave oven crash is not acceptable.
It was portable, so it could run on different pieces of hardware.
In 1994, the members of the Green project developed a World Wide Web (WWW) browser completely in Java that could run Java applets to demonstrate the power of the language. The browser was originally called WebRunner, but is now known as HotJava. Java came alive in 1995, however, when Netscape licensed the Java programming language and included support for it in its Navigator product.
In 1997, Sun released the Servlet API, which revolutionized server-side Web development and moved it away from monolithic CGI scripts or proprietary solutions. In 1999, Sun released the first version of the Java 2, Enterprise Edition (J2EE) specification that included JavaServer Pages (JSP) and Enterprise JavaBeans (EJB) in a highly distributed enterprise middleware. Since then the J2EE specification, along with the JSP, Servlet, and EJB specifications, have evolved into a very powerful programming paradigm.
Why Use Java?
You might have heard some of the geeks in your office talking about Java, or maybe you are taking a Java class in school, or perhaps you already know what Java is, but aren';t too sure why you would want to use it. Here are some reasons to learn Java, regardless of which category you fall under.
Java is a truly object-oriented programming language, perfect for modeling the real world and solving real-world problems. It will adapt to the latest design methodologies, and it provides extensibility so that your large project will be manageable.
Java is platform independent, so the same semicompiled byte code will work on Microsoft Windows, Unix, Apple Macintosh, Linux, and any future Wiz-bang operating system that implements a Java virtual machine.
Java can add interactivity to your Web pages. Java applets provide much of the functionality you are probably already familiar with, such as menus, data entry forms, and other user interface components as well as some of the neat drawings and animated graphics that are found on most Web pages.
With increasing CPU speeds, Java is becoming more feasible for building usable applications.
Java';s new SWING libraries rival components you see in the Microsoft Windows operating systems: tree controls, tab controls, list controls, tables, and so on.
Java has an incredible future in the upcoming decade! There is more and more talk about "intelligent devices" hosting a Java virtual machine that can run Java programs. These devices, such as smart toasters, smart televisions, and smart houses, will be networked together so that your television can tell your VCR to tell your toaster to start toasting! Java is the forefront technology of this exciting, evolving field.
Java has existed in its infancy for the past couple years, demonstrating conceptual leaps and bounds and accomplishing the unthinkable. As it evolves and matures, it is more and more apparent that Java will become the prevalent development language of the future. Learning Java will not only help you develop incredible applets and applications now, it will also prepare you for the future of computer and device programming!
Java Buzzwords
The following buzzwords are associated with Java; this section defines those buzzwords and explains how they are applicable to Java:
Simple
Object oriented
Distributed
Robust
Secure
Architecture neutral
Portable
Interpreted
Multithreaded
Simple
Java is simple to learn and simple to implement. Its syntax is very similar to C++ and C#, and it touts all the standard programming paradigms in an easy-to-use fashion. In fact, one of Java';s goals is to enable its developers to be up-and-running fast. Furthermore, it is consistent; when you learn how something works, you can rest assured that it will not change on you as you encounter a similar topic.
Object Oriented
Java is a truly object-oriented programming language that supports objects, inheritance, and polymorphism; this makes it ideal for establishing a good foundation in computer programming. We will discuss objects and object-oriented programming starting in Chapter 6, "Classes," but the main benefit of it is that you can model your Java programs after real-life objects, such as an apple, a car, or a person. This programming paradigm helps bridge the gap between the way a machine thinks and the way you do.
Distributed
Connectivity between components has been a basic tenet of the Java programming language since its inception. Java';s developers have remained true to this belief as the technology has evolved. Hence, developing applications that run on multiple machines concurrently and communicate with one another is far easier and efficient using Java than with many other programming languages.
Robust
Java';s modest beginnings as a simple mechanism to add interactivity to Web pages and develop simple communication schemes are a distant memory. Today Java boasts a graphical user interface (GUI) library that rivals features of the best operating systems; a Web development solution that surpasses any other offering; a distributed enterprise platform that leads the market; and a rich set of libraries for data input and output, multithreading, advanced imaging, XML document manipulation, and more. Almost any feature you could be searching for in a programming language you will find in Java.
Secure
Remember that Java';s inception was designed around the communication between smart devices. This legacy added a set of very strict rules governing what it can and cannot do. Various components of the Java programming language operate in different secure environments. For example, applets running in a Web browser cannot access a Web client';s underlying file system or any other Web site other than that from which it originated; a distributed component must be granted access to communicate with other hosts; and all Java programs run in a virtual machine that protects the underlying operating system from harm.
Architecture Neutral
Because Java runs inside of a Virtual Machine (a program written in operative system specific code that provides a common front-end to all operating systems) it in no way depends on the underlying operating system or hardware. Again this was another of the basic tenets of Java';s existence: to be able to run on any device.
Portable
Applications developed in Java are compiled into byte-code, which consists of instructions that a Virtual Machine will translate to operating system–specific instructions. Because of this, any Java code that you write and compile into byte-code will run on any operating system for which there exists a compatible Virtual Machine. Hence, the phrase: write once, run anywhere. The joke in the industry used to be write once, debug everywhere, but that is becoming less of a concern, especially in the server-side arenas.
Interpreted
Java is interpreted, which means that it is not compiled into machine-specific code until it is executed. Interpreted code tends to run much slower than fully compiled code, but Java gains some performance because it is partially compiled into byte-code. The partial compilation further benefits Java in that Java applications shipped to customers are not shipped as pure source code that can be easily read, but in a binary form.
Multithreaded
Multithreaded applications have the capability to run multiple things at the same time, for example a multithreaded application can display a graphical user interface to a user while downloading stock quotes from the Internet and computing historical averages. Java';s threading model was designed into the language from the beginning and is eloquently implemented, as you will learn later in the book.
Setting Up a Java Programming Environment
Before you can compile and execute a Java application, you must setup a Java programming environment. There are various Java compilers, but the standard is the one distributed on the Sun Web site. You can download the Java 2 SDK, Standard Edition from http://java.sun.com/j2se/.
On this page you will see three types of downloads for the latest released version and latest prereleased/release candidate (if available) version of Java. These three downloads are
Software Developers Kit (SDK)
Java Runtime Engine (JRE)
Documentation
The SDK is used to compile and execute Java programs; you will need to download this.
The JRE is used to execute Java programs, but does not contain anything for compiling them. People that use your Java applications will have to download and install JRE; the SDK includes the JRE so you don';t need to download it.
The documentation is specifically for users of the SDK. It lists and explains all the public classes in Java. I would highly recommend that you download and install this (it is viewable directly from the Internet). If you are short on disk space, then you can browse through the documentation as you need it.
As of this writing, the latest version of the Java 2, Standard Edition is version 1.4.
There are links to installation instructions presented to you when you download the SDK, but the following sections summarize the installation steps.
Microsoft Windows
The Java SDK for Microsoft Windows is an InstallShield­® file that guides you through the installation using wizard-like screens.
Download the SDK.
Launch the downloaded file.
Follow the prompts.
Linux
There are two versions of installation for Linux: a self-extracting binary file, and a binary file containing RPM packages.
Self-Extracting Binary
Download the SDK.
Copy the file to the directory where you want to install Java.
Grant the file execute privileges:
chmod a+x filename.bin
Execute the file:
./filename.bin
Follow the onscreen instructions.
RPM
RPM files, which are primarily used on Red Hat Linux, contain detailed installation instructions. RPM files are very easy to install and require little user interaction.
Download the SDK.
Grant the file execute privileges:
chmod a+x filename.rpm.bin
Execute the file:
./filename.rpm.bin
The result of this execution is the creation of a .rpm file. Execute the .rpm file as follows:
rpm -iv filename.rpm

Writing Your First Java Program
You can never escape the first chapter of a book without writing the traditional "Hello, World" application. Back in the early 1980s there was a book written by Brian Kernighan and Dennis Ritchie called The C Programming Language that was and is the de facto standard for C programming. In their book they defined the first example that all computer programming books should have: A program that writes the words "Hello, World" on the screen. Therefore, you will find a standard "Hello, World" example in almost every programming book you encounter. So, as not to break tradition, Listing 1.1 is "Hello, World" a la Java.
Listing 1.1 HelloWorld.java
1: public class HelloWorld
2: {
3:     public static void main( String[] args )
4:     {
5:         System.out.println( "Hello, World!" );
6:     }
7: }
Compiling Your First Java Program
Create a new file on your computer in a specific folder of your choice. For example, you might create a new file using Windows Notepad in the following folder:
C:\java
Enter the complete text of Listing 1.1 into your editor and save it with the following filename (note that case is important —capital "H" and "W" and all the rest of the letters are lowercase):
HelloWorld.java
If you are using Notepad, be sure to either enclose the filename in quotes ("HelloWorld.java") or check the filename when you are done, in some cases it likes to append a .txt to the end of the filename. If the filename is not correct, please correct it.
Open a command prompt and navigate to the folder where you saved your HelloWorld.java file. Using Windows as an example, open a command prompt, or MS-DOS prompt if you are using Windows 95, and enter the following command:
c:
cd \java
This will ensure that you are on the C: drive and change directory (cd) to the java subdirectory. Note that in this example you must have saved the file in this directory. Now you are ready to compile.
Compilation of Java programs is done at the command prompt using a tool that is packaged with the Java 2 SDK: javac read java see for Java Compiler. You compile a Java program by passing javac the name of the file you want to compile, for example:
javac HelloWorld.java
Upon executing the command you will see one of two possible responses: a new command prompt or a set of one or more errors. The most common error that my readers and students have when compiling Java programs has to do with an environment variable that Java depends on called CLASSPATH. The Java CLASSPATH is an interesting concept that often confuses not only new Java programmers, but experienced ones as well. The Java CLASSPATH is a list of folders that contain Java classes that you might want to include in your program, these define where your dependencies are located. If there is no CLASSPATH environment variable defined, the default value is the current folder. If there is one defined, the value must explicitly have the current folder in it if you want to compile from the current folder. To check the value of the CLASSPATH environment variable on your computer do the following:
Windows:
echo %CLASSPATH%
Unix:
echo $CLASSPATH
If the result is blank, then any errors you are receiving are not related to your CLASSPATH. If there is a value associated with the CLASSPATH environment variable, you must ensure that it includes the current folder. The CLASSPATH is simply a list of folders delimited by semicolons (;) on Windows and colons (:) on Unix. The current folder is specified by a period (.), which must appear in the CLASSPATH. To add the current folder to the CLASSPATH, enter the following:
Windows:
Add the current folder to the CLASSPATH
set CLASSPATH=.;%CLASSPATH%
Or to erase the CLASSPATH';s value
set CLASSPATH=
Unix:
CLASSPATH=.:$CLASSPATH; export CLASSPATH
At this point your CLASSPATH related errors should go away.
If you have other errors, here is a list of things to check:
Ensure that your Java code matches Listing 1.1: The case of all words must match identically, for example, class must be lowercase and "HelloWorld" must have a capital "H" and "W" and all remaining characters must be lowercase. Note that the formatting of the document does not affect the compilation, for example, if you want to write the entire program on one line or add 20 spaces between each line it would have no affect on the compiler.
Ensure that the name of your file is HelloWorld.java, again check the case of each letter, and if in Windows make sure Notepad did not add a .txt to the end of the filename. That can be accomplished by getting a directory of the folder your file is in by issuing a dir command (or ls in Unix):
dir
Ensure that you have the Java 2 SDK installed, and that the version you downloaded is the current version. To do so, execute the following command in the PATH:
java -version
Running Your First Java Program
After the HelloWorld.java file is successfully compiled, a new HelloWorld.class file is created. This is the file that contains the byte-code that contains instructions for the Java virtual machine to process. Java applications are run using the command-line tool java. To run HelloWorld, type the following from a command prompt in the folder that holds HelloWorld.class:
java HelloWorld
The result should be the following displayed to the screen:
Hello, World
If you receive an error, look at your CLASSPATH environment variable (see the discussion in the previous section for details).
Understanding Your First Java Program
It only took 7 lines to print "Hello, World" to the screen, and most of them have only one character each! Let';s look at this program line-by-line and see what is happening.
1: public class HelloWorld
In Java programs, .java files are compiled into byte-code with a .class extension. .class files can be thought of as the program itself. In this first line, a new class called HelloWorld is being defined. You can create new classes by using the keyword class followed by a name for the class.
Lines 2 and 7, the brace pair { and }, define the body of the HelloWorld class. Everything that is included between Lines 2 and 7 is part of the HelloWorld class.
3:     public static void main( String[] arguments )
Line 3 defines a method, or function if you would prefer, that is a member of the HelloWorld class called main. main is a very special function in Java, specifically for applications. main is the entry point that the Java Runtime Engine (JRE), or java.exe, processes when it starts. When you launch the application later by typing
java HelloWorld
you are telling the Java Runtime Engine to open the class file HelloWorld.class and process the main function. Let';s break down this function prototype further:
public
The keyword public is known as an access modifier; an access modifier defines who can and cannot see this function (or variable.) There are three possible values for access modifiers:
public, protected, and private, each having their own restrictions, which we will cover later in the book. In this case, it is saying that this function, main, is publicly available to anyone who wants to call it. This is essential for the main function; otherwise the Java Runtime Engine would not be able to access the function, and hence could not launch our application.
static
The static keyword tells the compiler that there is one and only one method (or variable) to be used for all instances of the class. For example, if you have 100 different copies of the HelloWorld class running, there will be only one main function. This functionality will be explained more later when you get a little more Java under your belt, but for now remember that main functions have to be static in a class.
void
The term void refers to the return type. Functions can return values; for example, integers, floating-point values, characters, strings, and more. If a function does not return any value, it is said to return void. In this declaration it is saying that the main function does not return a value.
main
The word main is the name of the function. As previously mentioned, main is a special function that must be defined when writing a Java application. It is the entry-point into your class that the Java Runtime Engine processes when it starts; it will control the flow of your program.
( String[] arguments )
Enclosed in parentheses next to the function name is the parameter list passed to the function. When you write a function, you can pass any type of data for that function to work with. In this case, the main function accepts an array (a collection or set of items) of String objects (text) that represent the command-line arguments the user entered when he launched the application.
java HelloWorld one two three four
The command line then would have four items sent to it: one, two, three, and four. The variable arguments would contain an array of these four strings. Here is how that would be listed:
arguments[0] = "one"
arguments[1] = "two"
arguments[2] = "three"
arguments[3] = "four"
Note that the indexes (0, 1, 2, and 3) start at zero and climb up to one, minus the total number of elements. This zero indexing is common to many programming languages such as C and C++ and programmers refer to the first element in an array as the "0-th element." This book will address arrays in detail a bit later.
Command-line arguments are beneficial because they can give a program additional infor-mation about what tasks to perform. For example, if you wanted to create an application that added two numbers and printed the result, you could take the two numbers to add from the command line, for example:
java AddApp 5 10
In the main function you would read in the numbers 5 and 10, and then print their sum to the screen.
Lines 4 and 6, the brace pair, denote the body of the main function; everything that is written between these braces is part of the main function.
5:         System.out.println( "Hello, World" );
Now this statement looks a little scary, but don';t fret, it is not nearly as intimidating as it looks. Let';s break apart this statement a bit:
System
System is actually a class that the Java language provides for you. This class is the focal point that you will use to access the standard input (keyboard), standard output (monitor), and standard error (usually a monitor unless you have a separate error output defined).
Note
Whenever you have questions about a class, you can always refer to the Java SDK documentation. Here is what the Java 2 SDK documentation has to say about the System class:
"The System class contains several useful class fields and methods. It cannot be instantiated."
Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined "properties;" a means of loading files and libraries; and a utility method for quickly copying a portion of an array.



The System class has a collection of public attributes, or data members, and a collection of public methods, or functions, that you can access in your program. You access these properties and methods by placing a period (.) after the class name System, and then appending to it the method or property name. The "." denotes a hierarchical movement through the object; the object to the left of the dot is the parent of the object to the right. In this example, we are going to access the System class';s out property.
out
The System class';s out property is defined as follows:
public static final PrintStream out
As with the main function, it is both public, meaning that everyone can access it, and static, meaning that there is only one copy of it for all instances of the System class. The final keyword says that this variable cannot change in value.
As I already mentioned, the out variable represents the standard output device, typically the monitor. Note that the out variable is of type PrintStream.
The PrintSteam class contains a collection of print, println, and write functions that know how to print different types of variables: Booleans, ints, floats, and so on. This is how println can print out so many different types of values.
Note
Here is what the Java 2 SDK documentation has to say about the out member variable:
"The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user."

Summary
This chapter discussed the fundamental concepts that empower Java as a powerful and productive programming language. It discussed the installation procedures and location of the Java 2 SDK Standard Edition, and then finished with writing your first Java program. Most of the discussion of your first Java program is probably still fuzzy, but now that you have a starting point, we will go through the entire Java programming language step-by-step so that this example will become trivial.
The next few chapters help you build a solid foundation into the Java programming language, starting with Chapter 2, "Keywords, Data Types, and Variables."


println
Okay, finally we are down to the function that actually does all the work for us! println has multiple definitions, one for each of the native data types (int, Boolean, float, double, String, and so on). The one that we are concerned with is declared as follows:
public void println(String x)
This version of the println function prints a String called x, which is what you send it, to an output stream.
Note
Here is what the Java 2 SDK documentation has to say about the println member variable:
"Print a String and then terminate the line. This method behaves as though it invokes print(String) and then println()."



You might have noticed that the PrintSteam class has both print and println member functions. The only difference here has to do with the line termination. print simply prints text to the screen, whereas println prints text to the screen followed by a new line.
"Hello, World"
Finally, you have the text String that you are telling println to print to the standard output device. The text string is enclosed in parentheses and delimited by double quotes ("").
Note that a semicolon terminates the very end of the statement. This is very important in the Java programming language. A semicolon terminates all statements; this is how the Java compiler knows where one statement ends and the next begins.

TOP

《Java 2 Primer Plus》

Chapter 2. Keywords, Data Types, and Variables
In this chapter you will learn:
Java';s keywords
Data types used in Java
Java variables
How memory is organized and how it is interpreted by Java variables
All programming languages define a set of keywords that represent instructions to the programming language compiler; data types that define how memory is allocated for items in memory such as numbers and characters; and variables that are used to name a region of memory. This chapter describes how these concepts are implemented in the Java programming language.
New Programmers
Before you can write a computer program, you must learn a set of rules that define how a computer program can be written. There are two sets of rules: syntax and semantics. Syntax defines the rules by which a program must adhere to be processed by the compiler. Semantics defines the logical rules that make a computer program do what you want it to.
The Java programming process is as follows:
You write a Java program and save it as a text file with the .java file extension.
The Java compiler reads your program and ensures that it is syntactically correct according to the rules of the language.
The Java compiler generates a new file with a .class file extension that contains byte-code instructions that will be later interpreted by a Java Virtual Machine (JVM).
A Java Virtual Machine interprets the byte-code and performs the instructions defined in it.
The results of the execution depend on the semantics of your program.
This chapter explains the basics of the Java programming language syntax.
Keywords
Keywords are the words in a program that offer specific instructions to the Java compiler. These words cannot be used as variable names because their presence in your Java program have very distinct meanings and can be thought of as placeholders for specific Java functionality.
The Java keywords are

abstract

boolean

break

byte

case

catch

char

class

const

continue

default

do

double

else

extends

false

final

finally

float

for

goto

if

implements

import

instanceof

int

interface

long

native

new

null

package

private

protected

public

return

short

static

super

switch

synchronized

this

throw

throws

transient

true

try

void

volatile

while

Each of these keywords will be discussed in detail as you read through this and the following chapters. For now pay particular attention so that you don';t use any of these words as names for your variables.

TOP

《Java 2 Primer Plus》

Data Types
A data type is a human-readable tag that represents a specific usage of a computer';s memory. When used in a program, it defines the amount of memory that will be used and the valid values that might be placed in that memory.
Java is a strongly typed programming language, meaning that all variables used in a Java program must have a specifically defined data type. A loosely typed programming language, such as JavaScript or Visual Basic, allows the use of the variable to define its type. For example, if a variable is used as a number, then it is a number, if it is used as a string of characters, then it is a string of characters. Because Java is a strongly typed language, we must define how a variable will be used before it can be defined.
The Computer/Human Communication Problem
Computers and humans speak two different languages. Humans think of things in terms of objects and define things in terms of numbers, letters, and words. Computers think in terms of 1s and 0s, which represent electrical impulses (1 = impulse, 0 = no impulse).
How can we translate our numbers, characters, and words into the 1s and 0s that computers understand?
Because computers do not have any inherent understanding of the number 5 or the letter B, we must define a representation of these using 1s and 0s, and then write rules that govern how certain operations on these values affect them. We can take the electrical signals, let';s call them bits, and group them into groups of 8 bits and call those bytes. So a byte will represent 8 bits, which is comprised of 1s and 0s. How might we represent a number with these 8 bits?
Our alphabet has 26 letters (A through Z), but we are now defining a computer';s alphabet as having two "letters": 0 and 1. Because we have only two numbers in our numerical alphabet, we must devise a way to count. In our decimal system we have 10 digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. In decimal we count as follows: 0 1 2 3 4 5 6 7 8 9, and then we start over with a two digit representation: 10 and proceed 11, 12, 13, and so on. If we count with two digits (binary) we start with 0, 1, and suddenly we are out of numbers. Following the decimal example, we now have our ten: 10, which if we are counting in our familiar decimal notation would be two—followed by 11 (or three), and hence we create the sequence: 0 1 10 11 100 101 110 111 1000 (or 1 2 3 4 5 6 7 8).
If we have 8 digits to work with that gives us 256 possible numbers in a single byte. But what about negative numbers? We can designate one bit as representing the sign of the number: Let';s say the highest bit (8th in this case) represents the sign (0 is positive and 1 is negative). Now we can represent 128 or 127 negative numbers, zero, and either 127 or 128 positive numbers (we have to count zero as one of our 256 possible numbers). If we were designing Java we would have decided to have 128 negative numbers and 127 positive numbers, thus with one byte, or 8 bits, or 8 electrical signals passing between circuits, we have a mechanism to represent numbers between –128 and +127.
The numbering system we just derived is referred to as binary notation, or base-2, where decimal is base-10. Each bit as we counted up represented a power of 2, see Figure 2.1.

Characters in Java are represented by the datatype char.
Boolean Data Type
Up to this point we have learned to represent whole numbers, fractional numbers, and characters, so what is left?
The last primitive data type in the Java programming language is the boolean data type. A boolean data type has one of two values: true or false. These are not strings, but keywords in the Java programming language.
Programming languages need to have boolean types so that they can perform specific actions based on predetermined conditions. For example, a program running a traffic light might have a sensor that tells it when people are waiting at the light. If people are waiting at the light (true), the light should prepare itself to change, otherwise it should remain unchanged (false).

TOP

《Java 2 Primer Plus》

Variables
Data types define the storage capacity and usage for a region in memory, but how is that memory accessible? Memory itself has a numerical address associated with it that, when accessed, references its value. If you think of memory linearly starting from 0 and ascending one value per byte you might represent your data as shown in Figure 2.3.

Figure 2.3 shows a simplistic view of how you might have a char, two ints, and a short stored in memory. Consider computing the sum of the two ints, how would you do it? Take the integer value stored in memory location 2–5 and add that to the integer value stored in memory location 8–11. Now let';s give them real-world meaning: Call the first integer the students in classroom 1, and the second integer the students in classroom 2. How many students are there in the two classrooms?
The answer is the sum of the integer value stored in memory location 2–5, and the integer value stored in memory at location 8–11. Not only is reading that unfriendly, I would venture to say that it is completely unusable! What are we to do?
Wouldn';t it be nice to associate a meaningful identifier with the portion of memory it refers to? For example we could call the memory location 2–5 classroomA, and the memory location 8–11 classroomB. Then, when asked for the total number of students we could answer with the following:
classroomA + classroomB
That is much easier to read and far more understandable.
In Java when you assign a meaningful identifier to a region of memory, that identifier is called a variable. Furthermore, you do not have to concern yourself with the actual location in memory that variable represents, that task can be delegated to the virtual machine, you only need to specify the data type and the variable name.
The act of creating a variable is called declaring a variable, and it has the following form:
datatype variableName;
The first thing you specify is the data type, which is one of the data types you learned about earlier in this chapter. Next is a meaningful name for your variable; you are free to use any name you want, with the following restrictions:
It must start with an alphabetic character (a through z, A through Z, or any Unicode character that denotes a letter in a language), an underscore, or the dollar sign.
It can have any alphabetic or numeric value as well as an underscore anywhere in its name.
It can be of unlimited length.
It cannot have any spaces or non-alphanumeric characters, such as + or -, in it.
It cannot be a Java keyword.
It is case sensitive (the case of a letter—uppercase or lowercase—has meaning, for example, myBook is not the same as myBooK.
The convention adopted by the Java world in naming variable is to start with a lowercase letter, and if the name has multiple words, capitalize the first letter of every word. For example:
thisIsMyVariableName
classroomA
totalNumberOfStudents
Finally, all variable declarations are terminated by a semicolon.
As an example consider the following variable declarations:
char c;
int numberOfStudentsInClassroom1;
float bankAccountBalance;
After a variable as been declared, a value can be assigned to it. Remember that its data type defines the valid values for a variable. Java defines an assignment operator for assigning values to variables: the equal sign (=). For example:
int myAge;
myAge = 30;
A line of Java code is called a statement, and a semicolon terminates each statement in Java. Another more common method of initializing a variable is to do so during its declaration. For example:
int myAge = 30;
This statement reads: define a variable named myAge that represents a 4-byte integer in memory and assign it the value 30.

TOP

《Java 2 Primer Plus》

Literals
A literal represents an actual character, string, or number and not a variable referencing, a character, string, or number in memory. The following are examples of literals:
1.0
';c';
"Happy"
7
In an expression (detailed in the next chapter) you might add 5 to an integer variable:
int n = a + 5;
In this case a is a variable and 5 is a literal value.
When defining numeric literals there are circumstances where you will have to tell the Java compiler how to interpret the value (what data type it is). When defining a floating-point number such as 1.0, the compiler automatically interprets the value as a double—if you want it to be interpreted as a float, you would have to append an f to it. For example:
float f = 1.0f
A failure to do so would result in a compilation error stating that you might lose precision in the assignment (because a double is represented by eight bytes and a float is only represented by four).

TOP

《Java 2 Primer Plus》

Conversion Between Numeric Types
Variables in Java can be participants in various operations including, but not limited to, addition, subtraction, multiplication, and division. These operations will be discussed in detail in the next chapter, but to complete the discussion of variables you need to know the general form. The general form of a mathematical operation in Java is
operand operator operand
Where a variable or a value is an operand and all mathematical operators are included as operators. Consider the following:
myApples + yourApples
The result is usually assigned to another variable using the assignment operator (=). The following adds myApples and yourApples and assigns them to the new integer totalApples:
int totalApples = myApples + yourApples;
When using numeric variables (variables defined to be ints, floats, and so on) the type does not necessarily have to be the same; in other words you can add an int to a byte. But what happens when you add an int to a byte? Remember that an int is 4 bytes, and a byte is just 1 byte. Take for example a byte with the value 100 and add an int with the value 1000 to it. The result is 1100, but how do we represent that in a byte? There simply are not enough bits to do it!
The answer is to convert the byte to be an int. This is referred to as arithmetic promotion. But what if we add a long, an int, and a byte? Should they all be promoted to a long?
All mathematical operations in Java are performed by promoting each operand in the operation to a specific data type, following these rules in this order:
If any of the operands is of type double, the other one will by converted to a double.
If any of the operands is of type float, the other one will be converted to a float.
If any of the operands is of type long, the other one will be converted to a long.
Otherwise all operands will be converted in ints.
The promotion, or conversion, of a narrower type (fewer number of bytes) to a wider type (greater number of bytes), such as the conversion of a short to an int, is accomplished by prepending the narrower type with enough bytes to be the same size as the wider type, and ensuring that the values are identical. For example, converting the byte 10 (written in binary):
0000 1010
To a short would result in the following:
0000 0000 0000 1010
Negative value conversions would be a little more complicated because the sign would have to maintained, but Java takes care of that for you.
These rules ensure that all operations resolve to the widest type (in number of bytes) in the operation. Thus, the result of the following operation is a long:
long l = 10;
int i = 10;
byte b = 10;
long result = l + i + b;
The int and byte are promoted to be longs before the operation is performed.
Conversion Through Assignment
You might have noticed that short and byte variables are promoted to ints during operations, even if there are no ints in the operation. Thus, the following statement would generate an unexpected error:
byte b1 = 10;
byte b2 = 10;
byte result = b1 + b2;
The Java compiler would complain about this operation saying that there is a "possible loss of precision" because although b1 and b2 are both bytes, they are promoted to ints before assigning the result to result. A byte has 1 byte, whereas an int has 4 bytes, so assigning an int to a byte loses the top 3 bytes during the assignment. Consider the integer 512, it is represented in binary as
0000 0000 0000 0000 0000 0010 0000 0000
If you remove the top 3 bytes, you have the following left:
0000 0000
Which is zero! That is why the compiler disallows the assignment of an int to a byte.
The rule for conversion between primitive numeric types is that a type can be assigned to a wider type (one with more bytes), but not a narrower type (one with less bytes). So, the following conversions are permissible by the compiler:
byte—short, int, long, float, double
short—int, long, float, double
int—long, float, double
long—float, double
float—double
char—int
For example:
int i = 10;
long l = i; // legal
double d = i; // legal
short s = i; // Illegal!

TOP

《Java 2 Primer Plus》

Casting Between Data Types
Does this mean that the result of your operations must be the data type of the largest data type in the operation? What if you, as the programmer, have knowledge of the nature of the data and can ensure that the data will not be lost?
Java offers a mechanism for overriding the compiler called casting. Casting tells the compiler to convert the data to the specified type even though it might lose data. By casting you are assuring the compiler that either data will not be lost, or if it is, that you will not care. Casting is performed by prefixing the variable or value by the desired data type enclosed in parentheses:
datatype variable = ( datatype )value;
For example:
int i = 10;
short s = ( short )i;
long l = 100;
byte b = ( byte )l;
Be sure that you do this with caution because the side effect of casting a variable to a narrower data type can result in the loss of data as you saw earlier.

TOP

《Java 2 Primer Plus》

Constants
Now that you have data types that represent memory in a specific way and variables as a convention to refer to that memory, how would you represent values that do not change, for example pi? You could define a variable named pi as follows:
double pi = 3.14285
When you need to use it, you could simply reference it in an equation:
double r = 10;
double area = pi * r * r;
Variables can, as their name implies, contain variable data. But because variables such as pi really cannot change, you must prevent the user from doing the following:
pi = pi / 2;
This is perfectly legal in Java, but violates the property of pi.
The answer is that we can declare a variable to be a constant, or not changing. Java uses the keyword final to denote that a variable is in fact a constant. Now you can preface your declaration of pi with the keyword final and ensure that its value cannot change:
final double pi = 3.14285
When you try to compile a statement that modifies a constant value, such as
final double pi = 3.14285
pi = pi / 2;
The compiler generates an error saying that you cannot assign a value to a final variable.
By convention, programmers usually capitalize all the letters in a constant';s name so that it can be found with only a casual glance of the source code. Pi, therefore, would be declared as follows:
final double PI = 3.14285

TOP

《Java 2 Primer Plus》

Summary
This chapter introduced you to some of the plumbing of the Java programming language: its keywords, the data types it supports, and the concept of named variables. The next couple chapters will build on this foundation and start getting you productive in your Java programming. When you are building a house you need both the tools and a set of plans to ensure that your house is built properly and does not fall down. Similarly in any programming language you need the tools—your keywords, data types, variables, operators, and so on—as well as the plans, a set of rules (syntax and semantics) to ensure that your program runs successfully.

TOP

《Java 2 Primer Plus》

Review Questions
1: Which of the following is not a keyword in Java?
int
label
continue
byte

2: What is the difference between syntax and semantics?

3: How do computers represent data?

4: What are data types? What do they do?

5: What is the difference between a short and an int?

6: Are the following statements legal? Why or why not?
short s1 = 10;
short s2 = 10;
short result = s1 + s2;

7: What is arithmetic promotion?

8: What types can you assign a short to without explicit casting?

9: What is casting and how do you do it?

10: How do you designate a variable to be a constant?


TOP

《Java 2 Primer Plus》

无奈本人的英语没学好,只能看懂一部分啊

TOP

返回列表 回复 发帖