A Simple Java Program

A Simple Java Program

简单的Java程序

Let's look more closely at about the simplest Java program you can have—one that simply prints a message to the console window:

让我们近距离的接触一个最简单的Java程序——仅仅是向控制台窗口输出一个信息的小程序:

public class FirstSample

{

   public static void main(String[] args)

   {

      System.out.println("We will not use 'Hello, World!'");

   }

}

 

It is worth spending all the time that you need to become comfortable with the framework of this sample; the pieces will recur in all applications. First and foremost, Java is case sensitive. If you made any mistakes in capitalization (such as typing Main instead of main), the program will not run.

你花费时间去消化这个例子的结构是值得的,因为这些部分会在所有的应用程序中再次出现。首先,也是最重要的,Java是区分大小写的。要是你出现了任何大小写错误(例如将Main写成main),程序就不会运行。

Now let's look at this source code line by line. The keyword public is called an access modifier; these modifiers control the level of access other parts of a program have to this code. We have more to say about access modifiers in Chapter 5. The keyword class reminds you that everything in a Java program lives inside a class. Although we spend a lot more time on classes in the next chapter, for now think of a class as a container for the program logic that defines the behavior of an application. As mentioned in Chapter 1, classes are the building blocks with which all Java applications and applets are built. Everything in a Java program must be inside a class.

现在,让我们一行一行的读这些源代码。关键字public叫做“访问调节器”,这些“调节器”控制这段代码访问程序其他部分的级别。我们将在第5章详细讨论“访问调节器”。关键字class提醒你在Java程序里所有的东西都存在于类中。虽然我们下一章要在类上花费大量的时间,但现在要清楚类就像一个程序逻辑的容器,它定义了应用程序的行为。正如在第1章中提到过的,类是组成所有Java应用程序和applet小程序的积木。Java编程中的所有东西都必须存在于类中。

Following the keyword class is the name of the class. The rules for class names in Java are quite generous. Names must begin with a letter, and after that, they can have any combination of letters and digits. The length is essentially unlimited. You cannot use a Java reserved word (such as public or class) for a class name. (See Appendix A for a list of reserved words.)

紧跟在关键字class后面的是类的名字。Java中类的命名规则相当宽松。名字只要以字母开头,后面可以接任何字母和数字的组合。长度原则上是没有限制的。但你不能用Java保留字(如publicclass)做名字。(参见附录A的保留字列表)

The standard naming convention (which we follow in the name FirstSample) is that class names are nouns that start with an uppercase letter. If a name consists of multiple words, use an initial uppercase letter in each of the words. (This use of uppercase letters in the middle of a word is sometimes called "camel case" or, self-referentially, "CamelCase.")

标准的命名约定(正如FirstSample所参照的)是以一个用大写字母开头的名词作为类的名字。如果一个名字有多个词组成,就把每个词的首字母都大写。(这种在一个词中间使用大写字母的方法有的时候被叫做“camel case”或者干脆“CamelCase”)

You need to make the file name for the source code the same as the name of the public class, with the extension .java appended. Thus, you must store this code in a file called FirstSample.java. (Again, case is important—don't use firstsample.java.)

你应该用与这个公共类(public class)相同的名字来作为这段代码的文件名,还要加上扩展名.java。因而,你必须把这段代码保存在叫做FirstSample.java的文件里。(再强调一次,注意大小写——不要用firstsample.java作为文件名)

If you have named the file correctly and not made any typos in the source code, then when you compile this source code, you end up with a file containing the bytecodes for this class. The Java compiler automatically names the bytecode file FirstSample.class and stores it in the same directory as the source file. Finally, launch the program by issuing the command:

如果你的文件命名正确,并且源代码没有任何打字错误,那么当你编译这段代码的时候,会得到一个包含这个类的二进制代码的文件。Java编译器会自动把这个二进制代码文件命名为FirstSample.class,并且保存在于源代码相同的目录下。最后,通过以下命令执行这个程序:

java FirstSample

 

(Remember to leave off the .class extension.) When the program executes, it simply displays the string We will not use 'Hello, World'! on the console.

(记得去掉扩展名.class)当这段程序运行的时候,只是在控制台上显示字符串We will not use ‘Hello, World’!

When you use

当你用

java ClassName

to run a compiled program, the Java virtual machine always starts execution with the code in the main method in the class you indicate. Thus, you must have a main method in the source file for your class for your code to execute. You can, of course, add your own methods to a class and call them from the main method. (We cover writing your own methods in the next chapter.)

运行编译完的程序,Java虚拟机总是从你指定的类的main方法中的代码开始执行。因此,在你的类的源代码文件中必须包含main方法以使你的代码可以被执行。当然,你也可以在类中加入你自己的方法并且从main方法中调用它们。(我们将在下一章涉及编写你自己的方法。)

NOTE

According to the Java Language Specification, the main method must be declared public. (The Java Language Specification is the official document that describes the Java language. You can view or download it from http://java.sun.com/docs/books/jls.) However, several versions of the Java launcher were willing to execute Java programs even when the main method was not public. A programmer filed a bug report. To see it, visit the site http://bugs.sun.com/bugdatabase/index.jsp and enter the bug identification number 4252539. However, that bug was marked as "closed, will not be fixed." A Sun engineer added an explanation that the Java Virtual Machine Specification (at http://java.sun.com/docs/books/vmspec) does not mandate that main is public and that "fixing it will cause potential troubles." Fortunately, sanity finally prevailed. The Java launcher in JDK 1.4 and beyond enforces that the main method is public.

依据《Java语言规范》,main方法必须被声明为public。(《Java语言规范》是描述Java语言的官方文档。你可以从http://java.sun.com/docs/books/jls 浏览或下载到它。)然而,个别版本的Java平台在main不是public的情况下也能够执行Java程序。已经有程序员提出了bug报告。你可以访问网站http://bugs.sun.com/bugdatabase/index.jsp并输入bug标识号4252539来查看这个报告。可是,那个bug被标记为“关闭,将不会被修复”。一个Sun工程师附加解释说,《Java虚拟机规范》(见http://java.sun.com/docs/books/vmspec 并没有要求mainpublic,而且“修复它将会引起潜在错误”。幸运的是,理智终将获胜。JDK 1.4及其后续版本开始强制要求main必须是public

There are a couple of interesting aspects about this story. On the one hand, it is frustrating to have quality assurance engineers, who are often overworked and not always experts in the fine points of Java, make questionable decisions about bug reports. On the other hand, it is remarkable that Sun puts the bug reports and their resolutions onto the Web, for anyone to scrutinize. The "bug parade" is a very useful resource for programmers. You can even "vote" for your favorite bug. Bugs with lots of votes have a high chance of being fixed in the next JDK release.

关于这个故事,有两个有趣的方面。一方面,它挫败了那些经常过度操劳,并且未必精通Java优点的质保工程师们对于bug报告所做出的值得怀疑的结论。另一方面,Sunbug报告和他们的结论放到网上供大家核对这一做法是值得关注的。“bug大阅兵”对程序员来说是非常有用的资源。你甚至可以为你关注的bug“投票”。得票多的bug将更有机会在下一个版本的JDK中被修复。

 

Notice the braces { } in the source code. In Java, as in C/C++, braces delineate the parts (usually called blocks) in your program. In Java, the code for any method must be started by an opening brace { and ended by a closing brace }.

注意在源代码中的大括号{ }。在Java中,如同在C/C++中一样,用大括号来标志程序中的各个部分(通常称为块)。在Java中,任何方法的代码都要以左括号“{”开头,以右括号“}”结束。

Brace styles have inspired an inordinate amount of useless controversy. We use a style that lines up matching braces. Because whitespace is irrelevant to the Java compiler, you can use whatever brace style you like. We will have more to say about the use of braces when we talk about the various kinds of loops.

大括号格式的灵感来自于缤纷杂乱的无用争论之中。我们使用一种对齐匹配大括号的格式。因为空白对于Java编译器是不起作用的,所以你可以使用任何你喜欢的大括号格式。在我们讨论各种循环的时候,会详细的说明括号的使用。

For now, don't worry about the keywords static void—just think of them as part of what you need to get a Java program to compile. By the end of Chapter 4, you will understand this incantation completely. The point to remember for now is that every Java application must have a main method that is declared in the following way:

目前,先不用担心关键字static void —— 只需把它们看成在Java程序编译时要用到的部分。在第4章的末尾,你就会完全明白这个“咒语”了。现在需要记住的是,每一个Java应用程序都必须有一个像下面那样声明的main方法:


public class ClassName
{

   
public static void main(String[] args)
   
{
      program statements
   
}
}

C++ NOTE

As a C++ programmer, you know what a class is. Java classes are similar to C++ classes, but there are a few differences that can trap you. For example, in Java all functions are methods of some class. (The standard terminology refers to them as methods, not member functions.) Thus, in Java you must have a shell class for the main method. You may also be familiar with the idea of static member functions in C++. These are member functions defined inside a class that do not operate on objects. The main method in Java is always static. Finally, as in C/C++, the void keyword indicates that this method does not return a value. Unlike C/C++, the main method does not return an "exit code" to the operating system. If the main method exits normally, the Java program has the exit code 0, indicating successful completion. To terminate the program with a different exit code, use the System.exit method.

作为C++程序员,你已经知道什么是类。Java类要比C++类简单,但有一些小小的区别会把你套进去。例如,在Java中,所有的函数都是类的方法(引用它们的标准的术语是“方法”而不是“元函数”)。因此,在Java中必须要将main方法放在一个外壳类里面。你也许熟悉C++中的静态元函数思想。在类中定义的元函数对对象不起作用。Java中的main方法总是静态的。最后,就像在C/C++中一样,关键字void指明这个方法没有返回值。与C/C++不同,main方法不会返回“退出码”给操作系统。如果main方法正常退出,Java程序会得到退出码0,表示成功结束。通过不同的退出码来结束程序,要使用System.exit方法。

 

Next, turn your attention to this fragment.

接下来,把你的注意力转移到下面的片断:

{

   System.out.println("We will not use 'Hello, World!'");

}

 

Braces mark the beginning and end of the body of the method. This method has only one statement in it. As with most programming languages, you can think of Java statements as being the sentences of the language. In Java, every statement must end with a semicolon. In particular, carriage returns do not mark the end of a statement, so statements can span multiple lines if need be.

大括号标志除了方法主体的开始和结束。这个方法仅包含一个语句。正如大多数程序语言,你可以把Java语句看成是这种语言的句子。在Java中,每个语句都必须以分号结尾。特别的,回车符并不表示一条语句的结束,因此,如果需要,一条语句可以跨越多行。

The body of the main method contains a statement that outputs a single line of text to the console.

main方法的主体包含一个向控制台输出单行文本的语句。

Here, we are using the System.out object and calling its println method. Notice the periods used to invoke a method. Java uses the general syntax

这里,我们使用System.out对象并调用它的println方法。注意这个周期通常调用一个方法。Java使用一般语法


object.method
(parameters)

for its equivalent of function calls.

来完成相当于函数调用的工作。

In this case, we are calling the println method and passing it a string parameter. The method displays the string parameter on the console. It then terminates the output line so that each call to println displays its output on a new line. Notice that Java, like C/C++, uses double quotes to delimit strings. (You can find more information about strings later in this chapter.)

在这个例子中,我们调用println方法并传递给它一个串参数。这个方法在控制台上显示这个串参数。然后它终止这个输出行以便其他的println调用将它们的输出显示在新的一行上。注意,JavaC/C++一样用双引号来标定字符串。(你可以在这一章稍后的部分找到关于字符串的更多信息。)

Methods in Java, like functions in any programming language, can use zero, one, or more parameters (some programmers call them arguments). Even if a method takes no parameters, you must still use empty parentheses. For example, a variant of the println method with no parameters just prints a blank line. You invoke it with the call

Java中的方法,像任何其他编程语言的函数一样,可以使用零个、一个或多个参数(有些程序员把他们称作自变量)。甚至如果一个方法没有参数,你都必须使用空的括号。例如,一种没有参数的println方法的变形可以用来输出一个空行。你要用如下语句调用:

System.out.println();

 

NOTE

System.out also has a print method that doesn't add a new line character to the output. For example, System.out.print("Hello") prints "Hello" without a new line. The next output appears immediately after the "o".

System.out也有一个不在输出中加入换行符的print方法。例如,System.out.print(“Hello”)就仅输出“Hello”而不换行。下一次输出会紧跟在“o”之后。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值