从今天开始,将follow数据结构的一门经典课程,UC Berkeley的CS61B。

1 Hello World

Let’s look at our first Java program. When run, the program below prints “Hello world!” to the screen.

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}

For those of you coming from a language like Python, this probably seems needlessly verbose. However, it’s all for good reason, which we’ll come to understand over the next couple of weeks. Some key syntactic features to notice:

  • The program consists of a class declaration, which is declared using the keywords public class. In Java, all code lives inside of classes.
  • The code that is run is inside of a method called main, which is declared as public static void main(String[] args).
  • We use curly braces { and } to denote the beginning and the end of a section of code. Statements must end with semi-colons.

2 Running a Java Program

The most common way to execute a Java program is to run it through a sequence of two programs. The first is the Java compiler, or javac. The second is the Java interpreter, or java.

For example, to run HelloWorld.java, we’d type the command javac HelloWorld.java into the terminal, followed by the command java HelloWorld. The result would look something like this:

$ javac HelloWorld.java
$ java HelloWorld
Hello World!

In the figure above, the $ represents our terminal’s command prompt. Yours is probably something longer.

You may notice that we include the ‘.java’ when compiling, but we don’t include the ‘.class’ when interpreting. This is just the way it is (TIJTWII).

3 Variables and Loops

The program below will print out the integers from 0 through 9.

public class HelloNumbers {
    public static void main(String[] args) {
        int x = 0;
        while (x < 10) {
            System.out.print(x + " ");
            x = x + 1;
        }
    }
}

When we run this program, we see:

$ javac HelloNumbers.java
$ java HelloNumbers
$ 0 1 2 3 4 5 6 7 8 9

Some interesting features of this program that might jump out at you:

  • Our variable x must be declared before it is used, and it must be given a type! Our loop definition is contained inside of curly braces, and the boolean expression that is tested is contained inside of parentheses.
  • Our print statement is just System.out.print instead of System.out.println. This means we should not include a newline (a return).
  • Our print statement adds a number to a space. This makes sure the numbers don’t run into each other. Try removing the space to see what happens.
  • When we run it, our prompt ends up on the same line as the numbers (which you can fix in the following exercise if you’d like).

4 Static Typing

One of the most important features of Java is that all variables and expressions have a so-called static type. Java variables can contain values of that type, and only that type. Furthermore, the type of a variable can never change.

One of the key features of the Java compiler is that it performs a static type check. For example, suppose we have the program below:

public class HelloNumbers {
    public static void main(String[] args) {
        int x = 0;
        while (x < 10) {
            System.out.print(x + " ");
            x = x + 1;
        }
        x = "horse";
    }
}

Compiling this program, we see:

$ javac HelloNumbers.java 
HelloNumbers.java:9: error: incompatible types: String cannot be converted to int
        x = "horse";
                ^
1 error

5 Extra Thought Exercise

In Java, we can say System.out.println(5 + " ");. But in Python, we can’t say print(5 + "horse"), like we saw above. Why is that so?

Consider these two Java statements:

String h = 5 + "horse";

and

int h = 5 + "horse";

The first one of these will succeed; the second will give a compiler error. Since Java is strongly typed, if you tell it h is a string, it can concatenate the elements and give you a string. But when h is an int, it can’t concatenate a number and a string and give you a number.

In this case, System.out.println(5 + "horse");, Java interprets the arguments as a string concatentation, and prints out “5horse” as your result. Or, more usefully, System.out.println(5 + " "); will print a space after your “5”.

6 Defining Functions in Java

In languages like Python, functions can be declared anywhere, even outside of functions. For example, the code below declares a function that returns the larger of two arguments, and then uses this function to compute and print the larger of the numbers 8 and 10:

def larger(x, y):
    if x > y:
        return x
    return y

print(larger(8, 10))

Since all Java code is part of a class, we must define functions so that they belong to some class. Functions that are part of a class are commonly called “methods”. We will use the terms interchangably throughout the course. The equivalent Java program to the code above is as follows:

public class LargerDemo {
    public static int larger(int x, int y) {
        if (x > y) {
            return x;
        }
        return y;
    }

    public static void main(String[] args) {
        System.out.println(larger(8, 10));
    }
}

The new piece of syntax here is that we declared our method using the keywords public static, which is a very rough analog of Python’s def keyword. We will see alternate ways to declare methods in the next chapter.

7 Code Style, Comments, Javadoc

In this course, we’ll work hard to try to keep our code readable. Some of the most important features of good coding style are:

Consistent style (spacing, variable naming, brace style, etc) Size (lines that are not too wide, source files that are not too long) Descriptive naming (variables, functions, classes), e.g. variables or functions with names like year or getUserName instead of x or f. Avoidance of repetitive code: You should almost never have two significant blocks of code that are nearly identical except for a few changes. Comments where appropriate. Line comments in Java use the // delimiter. Block (a.k.a. multi-line comments) comments use /* and */.

8 Comments

public class LargerDemo {
    /** Returns the larger of x and y. */           
    public static int larger(int x, int y) {
        if (x > y) {
            return x;
        }
        return y;
    }

    public static void main(String[] args) {
        System.out.println(larger(8, 10));
    }
}

9 Overview总结

关键语法功能:我们的第一个程序揭示了Java的几个重要语法特性:

  • 所有代码都存在于一个类中。
  • 执行的代码在称为main的函数(又称为方法)内部。
  • 花括号用于表示一段代码的开头和结尾,例如类或方法的声明。
  • 语句以分号结尾。
  • 变量具有声明的类型,也称为“静态类型”。
  • 变量必须在使用前声明。
  • 函数必须具有返回类型。如果函数不返回任何内容,则使用void,
  • 编译器确保类型一致性。如果类型不一致,则程序将无法编译。

静态类型: (我认为)静态类型是Java的最佳功能之一。与没有静态类型的语言相比,它为我们提供了许多重要的优势:

  • 在程序运行之前检查类型,使开发人员可以轻松捕获类型错误。
  • 如果编写程序并分发编译的版本,则(大多数)可以保证该程序没有任何类型错误。这使您的代码更可靠。
  • 每个变量,参数和函数都有一个声明的类型,从而使程序员更易于理解和推理代码。
  • 静态类型的缺点,将在后面讨论。

编码风格:编码风格在61B和现实世界中非常重要。应按照教科书和讲座中的说明对代码进行适当的注释。

命令行编译和执行javac用于编译程序。 java用于执行程序。我们必须始终在执行之前进行编译。