Topics in this section include:
本节主题包括:
What makes Java programs portable, secure, and robust
是什么使Java程序具有可移植性、安全性和健壮性
The structure of Java applets and applications
Java小程序和应用程序的结构
How Java applications are executed
Java应用程序的执行方式
How applets are invoked and executed
如何调用和执行小程序
The Java Language, Part I
Java语言,第一部分
Portability
可移植性
Java programs are portable across operating systems and hardware environments. Portability is to your advantage because
Java程序可以跨操作系统和硬件环境移植。可移植性是你的优势,因为
You need only one version of your software to serve a broad market.
你只需要一个版本的软件就可以服务于广阔的市场。
The Internet, in effect, becomes one giant, dynamic library.
实际上,互联网已经成为一个巨大的、动态的图书馆。
You are no longer limited by your particular computer platform.
您不再受特定计算机平台的限制。
Three features make Java String programs portable:
有三个特性使Java字符串程序可移植:
1. The language. The Java language is completely specified; all data-type sizes and formats are defined as part of the language. By contrast, C/C++ leaves these "details" up to the compiler implementor, and many C/C++ programs therefore are not portable.
1. 语言。Java语言是完全指定的;所有数据类型大小和格式都被定义为该语言的一部分。相比之下,C/C++将这些“细节”留给编译者实现,因此许多C/C++程序是不可移植的。
2. The library. The Java class library is available on any machine with a Java runtime system, because a portable program is of no use if you cannot use the same class library on every platform. Window-manager function calls in a Mac application written in C/C++, for example, do not port well to a PC.(Byte accounts for 1 byte, short for 2 bytes, int for 4 bytes, long for 8 bytes, float for 4 bytes, double for 8 bytes, char for 2 bytes, Boolean for 4 bytes)
2. 库。Java类库在任何带有Java运行时系统的机器上都是可用的,因为如果不能在每个平台上使用相同的类库,那么可移植程序是没有用的。窗口管理器函数调用在用C/C++编写的MAC应用程序中,例如,不很好地向PC机端口传送。(byte 占1个字节,short 占2个字节,int 占4个字节,long 占8个字节,float 占4个字节,double 占8个字节,char 占2个字节,boolean 占4个字节)
The byte code. The Java runtime system does not compile your source code directly into machine language, an inflexible and nonportable representation of your program. Instead, Java programs are translated into machine-independent byte code. The byte code is easily interpreted and therefore can be executed on any platform having a Java runtime system.
字节码。Java运行时系统不会将源代码直接编译成机器语言,这是程序的一种不灵活和不可移植的表示形式。相反,Java程序被翻译成独立于机器的字节码。字节码易于解释,因此可以在具有Java运行时系统的任何平台上执行。
Security
安全性
The Java language is secure in that it is very difficult to write incorrect code or viruses that can corrupt/steal your data, or harm hardware such as hard disks. There are two main lines of defense:
Java语言是安全的,因为很难编写错误的代码或病毒,这些代码或病毒会损坏/窃取您的数据,或损害硬盘等硬件。主要有两条防线:
• Interpreter level:
•口译员级别:
• No pointer arithmetic
•无指针算法
• Garbage collection
•垃圾收集
• Array bounds checking
•阵列边界检查
• No illegal data conversions
•无非法数据转换
• Browser level (applies to applets only):
•浏览器级别(仅适用于小程序):
• Sockets back to host only
•插座仅回主机
• No calls to native methods
•不调用本机方法
Robustness
健壮性
The Java language is robust. It has several features designed to avoid crashes during program execution, including:
稳健性
Java语言是健壮的。它有几个旨在避免程序执行期间崩溃的功能,包括:
• No pointer arithmetic
•无指针算法
• Garbage collection--no bad addresses
•回收站--无错误地址
• Array and string bounds checking
•数组和字符串边界检查
• No jumping to bad method addresses
•无跳转到错误方法地址
• Interfaces and exceptions
•接口和异常
Java Program Structure
Java程序结构
A file containing Java source code is considered a compilation unit. Such a compilation unit contains a set of classes and, optionally, a package definition to group related classes together. Classes contain data and method members that specify the state and behavior of the objects in your program.
包含Java源代码的文件被视为编译单元。这样的编译单元包含一组类和一个包定义(可选),可以将相关类分组在一起。类包含指定程序中对象的状态和行为的数据和方法成员。
Java programs come in two flavors:
Java程序有两种风格:
• Standalone applications that have no initial context such as a pre-existing main window
•没有初始上下文的独立应用程序,如预先存在的主窗口
• Applets for WWW programming
•用于WWW编程的小程序
The major differences between applications and applets are:
应用程序和小程序之间的主要区别是:
• Applets are not allowed to use file I/O and sockets (other than to the host platform). Applications do not have these restrictions.
•小程序不允许使用文件I/O和套接字(主机平台除外)。应用程序没有这些限制。
• An applet must be a subclass of the Java Applet class. Aplications do not need to subclass any particular class.
•小程序必须是Java小程序类的子类。应用程序不需要对任何特定类进行子类化。
• Unlike applets, applications can have menus.
•与小程序不同,应用程序可以有菜单。
• Unlike applications, applets need to respond to predefined lifecycle messages from the WWW browser in which they're running.
•与应用程序不同,小程序需要响应运行所在的WWW浏览器中预定义的生命周期消息
Java Program Execution
Java程序执行
The Java byte-code compiler translates a Java source file into machine- independent byte code. The byte code for each publicly visible class is placed in a separate file, so that the Java runtime system can easily find it. If your program instantiates an object of class A, for example, the class loader searches the directories listed in your CLASSPATH environment variable for a file called A.class that contains the class definition and byte code for class A.
Java字节码编译器将Java源文件转换为与机器无关的字节码。每个公共可见类的字节码都放在一个单独的文件中,这样Java运行时系统就可以很容易地找到它。例如,如果程序实例化了类A的对象,则类装入器将在CLASSPATH环境变量中列出的目录中搜索名为A.class的文件,该文件包含类A的类定义和字节码。
There is no link phase for Java programs; all linking is done dynamically at runtime.
Java程序没有链接阶段;所有链接都是在运行时动态完成的。
The following diagram shows an example of the Java compilation and execution sequence for a source file named A.java containing public class A and non-public class B:
下图显示了包含公共类a和非公共类B的名为a.Java的源文件的Java编译和执行序列的示例:
Java programs are, in effect, distributed applications. You may think of them as a collection of DLLs (dynamically loadable libraries) that are linked on demand at runtime. When you write your own Java applications, you will often integrate your program with already-existing portions of code that reside on other machines.
实际上,Java程序是分布式应用程序。您可能认为它们是按需链接的DLL(动态可加载库)的集合 运行时。当您编写自己的Java应用程序时,通常会将程序与驻留在其他机器上的现有代码部分集。
A Simple Application
一个简单的应用程序
Consider the following trivial application that prints "hi there" to standard output:
考虑以下将“hi there”打印到标准输出的普通应用程序:
public class TrivialApplication {
// args[0] is first argument
// args[1] the second
public static void main(String args[]) {
System.out.println("hi there");
}
}
public公共的,公开的,first argument第一个参数,the second第二个,static静的,静态的,void无效,无返回值,空,main主要的,string args字符串参数,System.out.println系统输出打印
The command java TrivialApplication tells the Java runtime system to begin with the class file TrivialApplication.class and to look in that file for a method with the signature:
命令java TrivialApplication告诉java运行时系统从类文件开始应用程序类在该文件中查找具有签名的方法:
public static void main(String args[]);
The main() method will always reside in one of your class files. The Java language does not allow methods outside of class definitions. The class, in effect, creates scoped symbol StartingClassName.main for your main() method.
main()方法将始终驻留在一个类文件中。Java语言不允许类定义之外的方法。实际上,类创建了作用域符号StartingClassName.main对于main()方法。
Applet Execution
小程序执行
An applet is a Java program that runs within a Java-compatible WWW browser or in an appletviewer. To execute your applet, the browser:
小程序是一种Java程序,它在与Java兼容的WWW浏览器或应用程序查看器中运行。要执行小程序,浏览器:
• Creates an instance of your applet
•创建小程序的实例
• Sends messages to your applet to automatically invoke predefined lifecycle methods
•向小程序发送消息以自动调用预定义的生命周期方法
The predefined methods automatically invoked by the runtime system are:
运行时系统自动调用的预定义方法包括:
init().ThismethodtakestheplaceoftheAppletconstructorandisonlycalled once during applet creation. Instance variables should be initialized in this method. GUI components such as buttons and scrollbars should be added to the GUI in this method.
•init()。此方法代替小程序构造函数,在创建小程序期间只调用一次。实例变量应在此方法中初始化。在此方法中,应该将按钮和滚动条等GUI组件添加到GUI中。
start(). This method is called once after init() and whenever your applet is revisited by your browser, or when you deiconify your browser. This method should be used to start animations and other threads.
•start()。此方法在init()之后以及浏览器重新访问小程序时或取消浏览器身份时调用一次。此方法应用于启动动画和其他线程。
paint(Graphicsg).Thismethodiscalledwhentheappletdrawingareaneeds to be redrawn. Anything not drawn by contained components must be drawn in this method. Bitmaps, for example, are drawn here, but buttons are not because they handle their own painting.
paint(Graphicsg)。当需要重新绘制小程序绘图区域时,将调用此方法。任何未由包含的组件绘制的内容都必须在此方法中绘制。例如,位图是在这里绘制的,但是按钮不是,因为它们处理自己的绘制。
stop().Thismethodiscalledwhenyouleaveanappletorwhenyouiconify your browser. The method should be used to suspend animations and other threads so they do not burden system resources unnecessarily. It is guaranteed to be called before destroy().
stop()。离开小程序或图标化浏览器时,将调用此方法。该方法应该用于挂起动画和其他线程,这样它们就不会给系统资源带来不必要的负担。它保证在destroy()之前被调用。
destroy().Thismethodiscalledwhenanappletterminates,forexample,when quitting the browser. Final clean-up operations such as freeing up system resources with dispose() should be done here. The dispose() method of Frame removes the menu bar. Therefore, do not forget to call super.dispose() if you override the default behavior.
destroy()。当小程序终止时(例如退出浏览器时)调用此方法。最后的清理操作,比如用dispose()释放系统资源,应该在这里完成。Frame的dispose()方法删除菜单栏。所以,别忘了打电话 super.dispose()如果重写默认行为。
Comments
注释
Java comments are the same as C++ comments, i.e.,
java注释与C++注释相同,即
/* C-style block comments */
/*C样式块注释*/
where all text between the opening /* and closing */ is ignored, and
忽略开头/*和结尾*/之间的所有文本,以及
// C++ style single-line comments
//C++风格的单行注释
where all text from the opening // to the end of the line is ignored.
从开头//到行尾的所有文本都被忽略。
Note that these two comments can make a very useful combination. C-style comments (/* ... */) cannot be nested, but can contain C++ style comments. This leads to the interesting observation that if you always use C++-style comments (// ...), you can easily comment out a section of code by surrounding it with C-style comments. So try to use C++ style comments for your "normal" code commentary, and reserve C-style comments for commenting out sections of code.
请注意,这两个注释可以构成非常有用的组合。C样式注释(/*。。。*/)不能嵌套,但可以包含C++风格的注释。这就引起了一个有趣的观察,如果你总是使用C++风格的注释(//…),你可以通过用C风格的注释来包围它来轻松地注释一段代码。因此,尝试使用C++风格的注释来进行“正常”代码注释,并保留C风格的注释来注释代码段。
The Java language also has a document comment:
Java语言还有一个文档注释:
/** document comment */
/**文件注释*/
These comments are processed by the javadoc program to generate documentation from your source code. For example,
这些注释由javadoc程序处理以生成源代码中的文档。例如,
/** This class does blah blah blah */
/**这类什么都没有*/
class Blah {
/** This method does nothing
这种方法不起任何作用
/**
* This is a multiple line comment.
* The leading * is not placed in documentation.
*/
/**
这是多行注释。
前导
不在文档中。
*/
public void nothing() {;}
}
Declarations
声明
A Java variable may refer to an object, an array, or an item of primitive type. Variables are defined using the following simple syntax:
Java变量可以引用一个对象、一个数组或一个基元类型的项。使用以下简单语法定义变量:
TypeName variableName;
类型名,变量名;
For example,
例如
int a; // defines an integer
定义一个整数
int[] b; // defines a reference to array of ints
定义对整数数组的引用;
Vector v; // reference to a Vector object
对向量对象的引用基本类型
Primitive Types
基本类型
The Java language has the following primitive types:
Java语言有以下基本类型:
Primitive Types
基本类型
boolean
true/false
byte
8 bit
char
16 bits (UNICODE)
short
16 bits
int
32 bits
long
64 bits
float
32 bits IEEE 754-1985
double
64 bits IEEE 754-1985
Java int types may not be used as boolean types and are always signed.
java int类型不能用作布尔类型,并且总是有符号
Objects
对象
A simple C++ object or C struct definition such as "Button b;" allocates memory on the stack for a Button object and makes b refer to it. By contrast, you must specifically instantiate Java objects with the new operator. For example,
一个简单的C++对象或C结构定义,比如“按钮B”,在按钮对象的堆栈上分配内存,并使B引用它。相反,您必须用新操作符具体地实例化Java对象。例如,
As the accompanying figure shows, this code places a reference b to the Button object on the stack and allocates memory for the new object on the heap.
如附图所示,此代码将引用b放置到堆栈上的Button对象,并为堆上的新对象分配内存。
The equivalent C++ and C statements that would allocate memory on the heap would be:
将在堆上分配内存的等效C++和C语句将是:
// C++ code
c++代码
Button *b = NULL;
// declare a new Button pointer
声明一个新按钮指针
b = new Button("OK");
// point it to a new Button
指向一个新按钮
/* C code */
c代码
Button *b = NULL;
/* declare a new Button pointer */
声明一个新的按钮指针
b = calloc(1, sizeof(Button));
/* allocate space for a Button */
为按钮分配空间
init(b, "OK");
/* something like this to init b */
类似于这样的内容到init b
All Java objects reside on the heap; there are no objects stored on the stack. Storing objects on the heap does not cause potential memory leakage problems because of garbage collection.
所有Java对象都驻留在堆上;堆栈上没有存储任何对象。在堆上存储对象不会因为垃圾收集而导致潜在的内存泄漏问题。
Each Java primitive type has an equivalent object type, e.g., Integer, Byte, Float, Double. These primitive types are provided in addition to object types purely for efficiency. An int is much more efficient than an Integer.
每个Java原语类型都有一个等价的对象类型,例如Integer、Byte、Float、Double。除了对象类型之外,还提供这些基本类型纯粹是为了提高效率。整数比整数有效得多。
Strings
字符串
Java string literals look the same as those in C/C++, but Java strings are real objects, not pointers to memory. Java strings may or may not be null-terminated. Every string literal such as
java字符串文字看起来与C++中的文字相同,但是java字符串是真实对象,而不是指向内存的指针。Java字符串可能以null结尾,也可能不以null结尾。每个字符串文本,例如
"a string literal"
字符串文字
is interpreted by the Java compiler as
由Java编译器解释为
new String("a string literal")
Java strings are constant in length and content. For variable-length strings, use StringBuffer objects.
Java字符串的长度和内容是恒定的。对于可变长度字符串,请使用StringBuffer对象。
Strings may be concatenated by using the plus operator:
可以使用加号运算符连接字符串:
String s = "one" + "two"; // s == "onetwo"
String s=“1”+“2”;//s==“1 2”
You may concatenate any object to a string. You use the toString() method to convert objects to a String, and primitive types are converted by the compiler. For example,
可以将任何对象连接到字符串。使用toString()方法将对象转换为字符串,编译器将转换基元类型。例如,
String s = "1+1=" + 2; // s == "1+1=2"
The length of a string may be obtained with String method length(); e.g."abc".length() has the value 3. To convert an int to a String, use:
字符串的长度可以通过string方法length()获得;例如,“abc”.length()的值为3。
String s = String.valueOf(4); To convert a String to an int, use:
要将int转换为字符串,请使用:
int a = Integer.parseInt("4");
Garbage Collection
垃圾收集
An automatic garbage collector deallocates memory for objects that are no longer needed by your program, thereby relieving you from the tedious and error-pronetask of deallocating your own memory.
自动垃圾收集器为程序不再需要的对象释放内存,从而将您从释放自己内存的繁琐且容易出错的任务中解脱出来。
As a consequence of automatic garbage collection and lack of pointers, a Java object is either null or valid--there is no way to refer to an invalid or stale object (one that has been deallocated).
由于自动垃圾收集和缺少指针,Java对象要么为null,要么为有效对象——无法引用无效或过时的对象(已释放的对象)。
To illustrate the effect of a garbage collector, consider the following C++ function that allocates 1000 objects on the heap via the new operator (a similar C function would allocate memory using calloc/malloc):
为了说明垃圾回收器的效果,考虑下面的C++函数,通过新的操作符在堆上分配1000个对象(类似的C函数将使用CALLC/MALLC分配内存):
// C++ code
void f() {
T *t;
for (int i = 1; i <= 1000; i++) {
t = new T; // ack!!!!!
}
}
Every time the loop body is executed, a new instance of class T is instantiated, and t is pointed to it. But what happens to the instance that t used to point to? It's still allocated, but nothing points to it and therefore it's inaccessible. Memory in this state is referred to as "leaked" memory.
每次执行循环体时,都会实例化一个类T的新实例,并将T指向它。但是t过去所指的那个例子会发生什么呢?它仍然是分配的,但没有指向它,因此无法访问。这种状态的内存称为“泄漏”内存。
In the Java language, memory leaks are not an issue. The following Java method causes no ill effects:
在Java语言中,内存泄漏不是问题。以下Java方法不会产生不良影响
// Java code
void f() { T t;
for (int i = 1; i <= 1000; i++) {
t = new T(); }
}
In Java, each time t is assigned a new reference, the old reference is now available for garbage collection. Note that it isn't immediately freed; it remains allocated until the garbage collector thread is next executed and notices that it can be freed.
在Java中,每当t被分配一个新的引用时,旧的引用现在就可以用于垃圾收集。请注意,它不会立即被释放;它将保持分配状态,直到垃圾收集器线程下一次执行并注意到它可以被释放。
Put simply, automatic garbage collection reduces programming effort, programming errors, and program complexity.
简单地说,自动垃圾收集减少了编程工作、编程错误和程序复杂性。