Introduction to Basic Syntax in Java – Java中的基本语法介绍

最后修改: 2019年 1月 1日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Java is a statically-typed, object-oriented programming language. It’s also platform-independent — Java programs can be written and compiled on one type of machine, such as a Windows system, and executed on another, such as MacOS, without any modification to the source code.

Java是一种静态类型的、面向对象的编程语言。它还具有平台独立性–Java程序可以在一种机器上编写和编译,如Windows系统,并在另一种机器上执行,如MacOS,而无需对源代码进行任何修改。

In this tutorial, we’re going to look at and understand the basics of Java syntax.

在本教程中,我们要看一看并了解Java语法的基本知识。

2. Data Types

2.数据类型

There are two broad categories of data types in Java: primitive types and objects/reference types.

Java中的数据类型有两大类。原始类型和对象/引用类型

Primitive types are the basic data types that store simple data and form the foundation of data manipulation. For example, Java has primitive types for integer values (int, long, byte, short)floating-point values (float and double)character values (char), and logical values (boolean).

原始类型是存储简单数据的基本数据类型,构成数据操作的基础。例如,Java有用于整数值(int, long,byte, short浮点值(floatdouble字符值(char)和逻辑值(boolean)的原始类型。

On the other hand, reference types are objects that contain references to values and/or other objects, or to the special value null to denote the absence of value.

另一方面,引用类型是包含对值和/或其他对象的引用的对象,或者包含表示没有值的特殊值null

The String class is a good example of a reference type. An instance of the class, called an object, represents a sequence of characters, such as “Hello World”.

String类是一个引用类型的好例子。该类的一个实例,称为对象,代表一个字符序列,如 “Hello World”。

3. Declaring Variables in Java

3.在Java中声明变量

To declare a variable in Java, we must specify its name (also called an identifier) and type. Let’s see a simple example:

要在Java中声明一个变量,我们必须指定其名称(也叫标识符)和类型。让我们看一个简单的例子。

int a;
int b;
double c;

In the above example, the variables will receive default initial values based on their declared types. Since we declared our variables to be int and double, they’ll have a default of 0 and 0.0, respectively.

在上面的例子中,变量将根据其声明的类型获得默认的初始值。由于我们声明我们的变量是intdouble,它们的默认值将分别为0和0.0。

Alternatively, we can use the assignment operator (=) to initialize variables during declaration:

另外,我们可以在声明时使用赋值运算符(=)来初始化变量:

int a = 10;

In the above example, we declare a variable with an identifier a to be of type int and assign a value of 10 to it using the assignment operator (=) and terminate the statement with a semi-colon (;). It’s compulsory, in Java, that all statements end with a semi-colon.

在上面的例子中,我们用标识符a声明一个类型int的变量,给它赋值10使用赋值运算符(=)并以分号(;)结束该语句。

An identifier is a name of any length, consisting of letters, digits, underscore, and dollar sign, that conforms to the following rules:

标识符是一个由字母、数字、下划线和美元符号组成的任何长度的名称,符合以下规则。

  • starts with a letter, an underscore (_), or a dollar sign ($)
  • can’t be a reserved keyword
  • can’t be true, false, or null

Let’s expand our code snippet above to include a simple arithmetic operation:

让我们扩展上面的代码片段,包括一个简单的算术操作。

int a = 10;
int b = 5;
double c = a + b;
System.out.println( a + " + " + b + " = " + c);

We can read the first three lines of the code snippet above as “assign the value of 10 to a, assign the value of 5 to b, sum the values of and b and assign the result to c”. In the last line, we output the result of the operation to the console:

我们可以将上述代码片段的前三行解读为“将10的值赋给a,将5的值赋给b,ab的值相加,将结果赋给c”。在最后一行,我们将操作的结果输出到控制台。

10 + 5 = 15.0

Declaration and initialization of variables of other types follow the same syntax that we’ve shown above. For example, let’s declare String, char, and boolean variables:

其他类型的变量的声明和初始化遵循我们上面展示的相同语法。例如,让我们声明Stringcharboolean变量。

String name = "Baeldung Blog";
char toggler = 'Y';
boolean isVerified = true;

For emphasis sake, the main difference in representing literal values of char and String is the number of quotes that surrounds the values. Therefore, ‘a’ is a char while “a” is a String.

为了强调起见,表示charString的字面价值的主要区别是围绕这些价值的引号的数量。因此,‘a’是一个char,而“a”是一个String

4. Arrays

4.数组

An array is a reference type that can store a collection of values of a specific type. The general syntax for declaring an array in Java is:

数组是一种引用类型,可以存储特定类型的值的集合。在Java中声明数组的一般语法是:。

type[] identifier = new type[length];

type[] identifier = new type[length];

The type can any primitive or reference type.

该类型可以是任何原始类型或引用类型。

For example, let’s see how to declare an array that can hold a maximum of 100 integers:

例如,让我们看看如何声明一个最多可容纳100个整数的数组。

int[] numbers = new int[100];

To refer to a specific element of an array, or to assign a value to an element, we use the variable name and its index:

为了引用一个数组中的特定元素,或者为一个元素赋值,我们使用变量名和它的索引。

numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
int thirdElement = numbers[2];

In Java, array indexes start at zero. The first element of an array is at index 0, the second element is at index 1, and so on.

在Java中,数组索引从0开始。数组的第一个元素的索引是0,第二个元素的索引是1,以此类推。

Additionally, we can get the length of the array by calling numbers.length:

此外,我们可以通过调用numbers.length获得数组的长度。

int lengthOfNumbersArray = numbers.length;

5. Java Keywords

5.Java关键词

Keywords are reserved words that have special meaning in Java.

关键词是在Java中具有特殊意义的保留词。

For example, public, static, class, main, new, instanceof, are keywords in Java, and as such, we can’t use them as identifiers (variable names).

例如,public、static、class、main、new、instanceof,是Java中的关键词,因此,我们不能将它们作为标识符(变量名)

6. Operators in Java

6.Java中的操作符

Now that we’ve seen the assignment operator (=) above, let’s explore some other types of operators in the Java language:

现在我们已经看到了上面的赋值运算符(=),让我们来探讨一下Java语言中其他类型的运算符

6.1. Arithmetic Operators

6.1.算术运算符

Java supports the following arithmetic operators that can be used for writing mathematical, computational logic:

Java支持以下算术运算符,可用于编写数学、计算逻辑。

  • + (plus or addition; also used for string concatenation)
  • – (minus or subtraction)
  • * (multiplication)
  • / (division)
  • % (modulus or remainder)

We’ve used the plus (+) operator in our previous code example to perform addition of two variables. The other arithmetic operators are used similarly.

我们在之前的代码示例中使用了加号(+)运算符来执行两个变量的加法。其他算术运算符的使用方法与此类似。

Another use of plus (+) is for concatenation (joining) of strings to form a whole new string:

加号(+)的另一个用途是串联(连接)字符串,形成一个全新的字符串。

String output =  a + " + " + b + " = " + c;

6.2. Logical Operators

6.2.逻辑运算符

In addition to arithmetic operators, Java supports the following logical operators for evaluating boolean expressions:

除了算术运算符之外,Java还支持以下逻辑运算符,用于评估布尔表达式。

  • && (AND)
  • || (OR)
  • ! (NOT)

Let’s consider the following code snippets that demonstrate the logical AND and OR operators. The first example shows a print statement that executes when the number variable is divisible both by 2 AND by 3:

让我们考虑一下下面的代码片断,它们展示了逻辑运算符AND和OR。第一个例子显示了一个打印语句,当number变量既能被2又能被3整除时执行。

int number = 6;
        
if (number % 2 == 0 && number % 3 == 0) {
    System.out.println(number + " is divisible by 2 AND 3");
}

While the second is executed when number is divisible by 2 OR by 5:

number能被2或5整除时,第二种情况会被执行。

if (number % 2 == 0 || number % 5 == 0) {
    System.out.println(number + " is divisible by 2 OR 5");
}

6.3. Comparison Operators

6.3.比较运算符

When we need to compare the value of one variable to that of another, we can use Java’s comparison operators:

当我们需要将一个变量的值与另一个变量的值进行比较时,我们可以使用Java的比较运算符

  • < (less than)
  • <= (less than or equal to)
  • > (greater than)
  • >= (greater than or equal to)
  • == (equal to)
  • != (NOT equal to)

For example, we can use a comparison operator to determine the eligibility of a voter:

例如,我们可以使用比较运算符来确定一个选民的资格。

public boolean canVote(int age) {
    if(age < 18) {
        return false;
    }
    return true;
}

7. Java Program Structure

7.Java程序结构

Now that we’ve learned about data types, variables, and a few basic operators, let’s see how to put these elements together in a simple, executable program.

现在我们已经了解了数据类型、变量和一些基本的运算符,让我们看看如何把这些元素放在一个简单的、可执行的程序中。

The basic unit of a Java program is a Class. A Class can have one or more fields (sometimes called properties)methods, and even other class members called inner classes.

Java程序的基本单元是一个一个可以有一个或多个字段(有时称为属性)方法,甚至还有其他称为内类的类成员。

For a Class to be executable, it must have a main method. The main method signifies the entry point of the program.

要使一个可执行,它必须有一个main方法。main方法标志着程序的进入点。

Let’s write a simple, executable Class to exercise one of the code snippets we considered earlier:

让我们写一个简单的、可执行的Class来练习我们前面考虑的一个代码片段。

public class SimpleAddition {

    public static void main(String[] args) {
        int a = 10;
        int b = 5;
        double c = a + b;
        System.out.println( a + " + " + b + " = " + c);
    }
}

The name of the class is SimpleAddition, and inside of it, we have a main method that houses our logic. The segment of code between an opening and closing curly braces is called a code block.

这个类的名字是SimpleAddition,在这个类中,我们有一个main方法,用来存放我们的逻辑。在大括号的开头和结尾之间的代码段被称为代码块。

The source code for a Java program is stored in a file with an extension of .java.

Java程序的源代码存储在一个扩展名为.java的文件中。

8. Compiling and Executing a Program

8.编译和执行一个程序

To execute our source code, we first need to compile it. This process will generate a binary file with the .class file extension. We can execute the binary file on any machine that has a Java Runtime Environment (JRE) installed.

为了执行我们的源代码,我们首先需要对它进行编译。这个过程将生成一个二进制文件,文件扩展名是.class。我们可以在任何安装了Java运行环境(JRE)的机器上执行这个二进制文件。

Let’s save our source code from the above example into a file named SimpleAddition.java and run this command from the directory where we’ve saved the file:

让我们把上述例子的源代码保存到一个名为SimpleAddition.java的文件中,然后从保存文件的目录中运行这个命令。

javac SimpleAddition.java

To execute the program, we simply run:

要执行该程序,我们只需运行。

java SimpleAddition

This will produce the same output to the console as shown above:

这将产生与上面所示相同的输出到控制台。

10 + 5 = 15.0

9. Conclusion

9.结论

In this tutorial, we’ve looked at some of the basic syntax of Java. Just like any other programming language, it gets simpler with constant practice.

在本教程中,我们已经了解了Java的一些基本语法。就像其他任何编程语言一样,通过不断的练习,它也会变得更简单。

The complete source code for this tutorial is available over on Github.

本教程的完整源代码可在Github.上获得。